本文共 992 字,大约阅读时间需要 3 分钟。
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
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means?
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean isSymmetric(TreeNode root) { if(null == root) return true; return isSymmetricUtil(root.left, root.right); } public boolean isSymmetricUtil(TreeNode root_1, TreeNode root_2) { if(null == root_1 && null == root_2) return true; else if(null != root_1 && null != root_2) { return root_1.val== root_2.val && isSymmetricUtil(root_1.left,root_2.right ) && isSymmetricUtil(root_2.left , root_1.right); }else return false; }}
转载地址:http://snuni.baihongyu.com/