爱程序网

[LeetCode] 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

     这道题也挺有意思的。不过首先要搞懂题目,首先搞清楚怎样的BTS才算symmetric的。必须要是一个balanced的BTS然后两边的height都相等。

     这道题个人觉得用recursive来写比较容易哈。

     代码如下。~

/**
 * Definition for a binary tree node.
 * 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;
        return symhelper(root.left,root.right);
    }
    
    public boolean symhelper(TreeNode left,TreeNode right){
        if(left==null||right==null){
            return (left==right);
        }
        if((left.val==right.val)&&(symhelper(left.left,right.right))&&(symhelper(left.right,right.left))){
            return true;
        }else{
            return false;
        }
    }
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助