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; } }}新聞熱點
疑難解答