码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode题目记录-11】判断二叉树是否是镜像的(对称的)

时间:2014-09-15 17:46:29      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:二叉树是否是镜像的对称的

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

【分析1-原创】采用递归方案,查看了参考才搞定。

参考:https://oj.leetcode.com/discuss/456/recusive-solution-symmetric-optimal-solution-inordertraversal

public static boolean isSymmetric(TreeNode root) {
         if(root==null) return true;
         return checkIsSymmetric(root.left,root.right);
    }
    private static boolean checkIsSymmetric(TreeNode leftNode,TreeNode rightNode) {
       if(leftNode==null&&rightNode==null) return true;
       if((leftNode!=null&&rightNode==null)||(leftNode==null&&rightNode!=null)) return false;
       if(leftNode.val!=rightNode.val) return false;
       return checkIsSymmetric(leftNode.left,rightNode.right)&&checkIsSymmetric(leftNode.right,rightNode.left);
} 


【分析2-非原创】用stack对左右进行进stack,然后每一层进行比较。

参考:https://oj.leetcode.com/discuss/456/recusive-solution-symmetric-optimal-solution-inordertraversal

   

 public boolean isSymmetric(TreeNode root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (root == null)
            return true;
        Stack<TreeNode> s1 = new Stack<TreeNode>();
        Stack<TreeNode> s2 = new Stack<TreeNode>();
        s1.push(root.left);
        s2.push(root.right);
        while (!s1.empty() && !s2.empty()) {
            TreeNode n1 = s1.pop();
            TreeNode n2 = s2.pop();
            if (n1 == null && n2 == null)
                continue;
            if (n1 == null || n2 == null)
                return false;
            if (n1.val != n2.val)
                return false;
            s1.push(n1.left);
            s2.push(n2.right);
            s1.push(n1.right);
            s2.push(n2.left);
        }
        return true;
    }

【LeetCode题目记录-11】判断二叉树是否是镜像的(对称的)

标签:二叉树是否是镜像的对称的

原文地址:http://blog.csdn.net/brillianteagle/article/details/39295289

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!