Symmetric Tree

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.

思路1:如果是用递归的方法,判断一个树是否为对称树,也就是要判断根结点的左边和右边是否对称,需要一个方法判断两棵子树是否对称,并且要注意递归的出口。

 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
         if(root==null) return true;
        else if(root.left==null && root.right==null) return true;
        else if(root.left==null || root.right==null) return false;
        else return isSymmetric(root.left,root.right);
    }
    public  boolean isSymmetric(TreeNode left,TreeNode right)
     {
        if(left==null&& right==null) return true;
         else if(left==null || right==null) return false;
         else if(left.val!=right.val)return false;
         else 
         { 
            return isSymmetric(left.left,right.right) && isSymmetric(left.right,right.left); 
         }
     }
}


思路2:如果是采用迭代的方法,同样也是要判断左右两边是否对称,然后需要借助于栈,自上往下去迭代,一个栈存储根节点左边的的子树,另一个栈存储根节点右边的子树,当然左边两边结点的入栈顺序是相反的,这个为了保证从栈中弹出的两个结点的位置相对于树来说是左边和右边对应的位置。直到栈中的结点全部出栈,这样整棵树就比较完了。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        TreeNode p = root;
        if (p == null)
            return true;
        Stack<TreeNode> stackLeft = new Stack<TreeNode>();
        Stack<TreeNode> stackRight = new Stack<TreeNode>();
        stackLeft.push(p.left);
        stackRight.push(p.right);
        while (stackLeft.size() > 0 && stackRight.size() > 0) {
            TreeNode node1 = stackLeft.pop();
            TreeNode node2 = stackRight.pop();
            if (node1 == null && node2 == null)
                continue;
            if (node1 == null || node2 == null)
                return false;
            if (node1.val != node2.val)
                return false;
            else {
                stackLeft.push(node1.left);
                stackLeft.push(node1.right);
                stackRight.push(node2.right);
                stackRight.push(node2.left);
            }

        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值