首页 > 其他 > 详细

[Leetcode]101. Symmetric Tree

时间:2017-11-04 16:07:24      阅读:184      评论:0      收藏:0      [点我收藏+]

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   /   2   2
 / \ / 3  4 4  3

 

But the following [1,2,2,null,3,null,3] is not:

    1
   /   2   2
   \      3    3

思路:设两个游标p,q同时递归,递归的方向相反。即当p往左走时,q往右走。p往右走时,q往左走。
如果这棵树是镜像的,那么最后 p 和 q一定是同时到达null位置,并且在这个过程中,p,q节点的
值是相同的。


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root==null)
            return true;
        return judge(root.left,root.right);
    }

    private  boolean judge(TreeNode p,TreeNode q){
        if (p==null&&q==null)               //同时到达null位置,说明树是镜像的
            return true;
        if (p==null&&q!=null)
            return false;
        if (p!=null&&q==null)
            return false;
        if (p.val!=q.val)
            return false;
        return judge(p.left,q.right)&&judge(p.right,q.left);
    }
}

 

[Leetcode]101. Symmetric Tree

原文:http://www.cnblogs.com/David-Lin/p/7783470.html

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