首页 > 学院 > 开发设计 > 正文

[LeetCode] Symmetric Tree

2019-11-15 01:16:28
字体:
来源:转载
供稿:网友
[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;        }    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表