这里A这道题的时候,刚看到题目的时候想到用递归。后面题目也有提示,用递归或迭代。还是没有弄出来,主要参考了
LeetCode Oj:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.confused what "{1,#,2,3}"
means?
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
. 1 class TreeNode { 2 int val; 3 TreeNode left; 4 TreeNode right; 5 TreeNode(int x) { val = x; } 6 } 7 8 public class Solution { 9 public boolean isSymmetric(TreeNode root) { 10 if(null == root)11 return true;12 return check(root.left, root.right);13 }14 public boolean check(TreeNode leftNode, TreeNode rightNode){ //开始有想到这样,用左右子节点15 if(null == leftNode && null == rightNode) //两个都是空节点16 return true;17 if(null == leftNode || null == rightNode)//其中一个空节点18 return false;19 //两个都不是空节点20 return leftNode.val == rightNode.val && check(leftNode.left, rightNode.right) 21 && check(leftNode.right, rightNode.left);//这里用的很漂亮,主要逻辑也在这里22 }23 }