首页 > 其他 > 详细

101. Symmetric Tree

时间:2019-03-15 16:10:12      阅读:163      评论:0      收藏:0      [点我收藏+]

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

 

Solution1:

class Solution {

    public boolean isSymmetric(TreeNode root) {

        return root == null || isSymmetricHelp(root.left, root.right);

    }

    public boolean isSymmetricHelp(TreeNode left, TreeNode right) {

    if (left == null)

    return right == null;

        if (right == null)

    return false;

        if (left.val != right.val) { //left.val不一定有值,所以要避免空指针异常

            return false;

        }

        return isSymmetricHelp(left.left, right.right) && isSymmetricHelp(left.right, right.left);

    }

}

Solution2://使用栈存放TreeNode,

class Solution {

    public boolean isSymmetric(TreeNode root) {

        if (root == null) return true;

        Stack<TreeNode> s = new Stack<>();

        s.push(root.left);

        s.push(root.right);

        while (!s.empty()) {

            TreeNode n1 = s.pop();

            TreeNode n2 = s.pop();

            if (n1 == null && n2 == null) continue;

            if (n1 == null || n2 == null || n1.val != n2.val) {

                return false; //上边的if已经考虑了n1和n2都是null了,所以如果上述if条件不满足且n1或n2又出现                                           null,那么肯定是一个null一个有数值,所以返回false

            }

            stack.push(n1.left);

            stack.push(n2.right);

            stack.push(n1.right);

            stack.push(n2.left);

       }

        return true;

}

101. Symmetric Tree

原文:https://www.cnblogs.com/MarkLeeBYR/p/10537303.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!