Symmetric Tree
Posted YuriFLAG
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
递归 check左子树和右子树是否为Symmetric Tree 。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isSymmetric(TreeNode root) { 12 if (root == null || root.left == null && root.right == null) { 13 return true; 14 } 15 return helper(root.left, root.right); 16 17 } 18 private boolean helper(TreeNode root1, TreeNode root2) { 19 if (root1 == null) { 20 return root2 == null; 21 } 22 if (root2 == null) { 23 return root1 == null; 24 } 25 if (root1.val != root2.val) { 26 return false; 27 } 28 return helper(root1.right, root2.left) && helper(root1.left, root2.right); 29 } 30 }
以上是关于Symmetric Tree的主要内容,如果未能解决你的问题,请参考以下文章