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? > read more on how binary tree is serialized on OJ.
分类:二叉树
题意:判断一棵二叉树是否对称
解法1:递归。判断是否左右子树是否相等。具体方法是如果都为空,则返回真,否则判断是否其中一个为空,或者值不相等,则返回假。否则最后递归判断左右子树。
-
-
-
-
-
-
-
-
-
- public class Solution {
- public boolean isSymmetric(TreeNode root) {
- if(root==null) return true;
- return solve(root.left, root.right);
- }
-
- public boolean solve(TreeNode left,TreeNode right){
- if(left==null&&right==null) return true;
- if((left!=null && right==null) || (left==null && right!=null)
- || (left.val!=right.val)) return false;
- return solve(left.left, right.right)&&solve(left.right, right.left);
- }
- }
解法2:使用栈代替递归。左子树顺序入栈,右子树反向入栈。
-
-
-
-
-
-
-
-
-
- public class Solution {
- public boolean isSymmetric(TreeNode root) {
- if(root==null) return true;
- Stack<TreeNode> leftStack = new Stack<TreeNode>();
- Stack<TreeNode> rightStack = new Stack<TreeNode>();
- leftStack.add(root.left);
- rightStack.add(root.right);
- while(leftStack.size()>0&&rightStack.size()>0){
- TreeNode left = leftStack.pop();
- TreeNode right = rightStack.pop();
- if(left!=null&&right==null) return false;
- if(left==null&&right!=null) return false;
- if(left!=null&&right!=null){
- if(left.val!=right.val) return false;
-
- leftStack.add(left.left);
- leftStack.add(left.right);
- rightStack.add(right.right);
- rightStack.add(right.left);
- }
- }
- return true;
- }
- }