public boolean isSymmetric(TreeNode root) {
return DFS(root, root);
}
public boolean DFS(TreeNode t1, TreeNode t2) {
if(t1 == null && t2 == null) return true;
if(t1 == null || t2 == null) return false;
return (t1.val == t2.val) && DFS(t1.left, t2.right)
&& DFS(t1.right, t2.left);
}
本题的关键点:
同时深度搜索t1, t2,也就是左和右同时搜索
ps:也有类似的题可以用这种同时搜索的做法,例如572. Subtree of Another Tree
public boolean isSubtree(TreeNode s, TreeNode t) {
ArrayList<TreeNode> list = new ArrayList<TreeNode>();
findNode(s, t.val, list);
for(int i = 0, len = list.size(); i < len; i++) {
if(check(list.get(i), t)) {
return true;
}
}
return false;
}
public void findNode(TreeNode node, int target, ArrayList<TreeNode> list) {
if(node == null) return;
if(node.val == target) {
list.add(node);
}
findNode(node.left, target, list);
findNode(node.right, target, list);
}
public boolean check(TreeNode t1, TreeNode t2) {
if(t1 == null && t2 == null) return true;
if(t1 == null || t2 == null) return false;
return (t1.val == t2.val) && check(t1.left, t2.left)
&& check(t1.right, t2.right);
}