For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Idea: Depth-first search. I used preorder traversal, compare current, then traverse (left.left, right.right) and (left.right, right.left) at the same time. Once a mismatch happens, stops and return.
Time: O(n) Space: O(lgn)
Code:
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
return dfs(root.left,root.right);
}
public boolean dfs(TreeNode left, TreeNode right)
{
if(left==null||right==null)
{
if(left==null&&right==null)
return true;
return false;
}
if(left.val!=right.val)
return false;
return dfs(left.left,right.right)&&dfs(left.right,right.left);
}
}
No comments:
Post a Comment