您的位置:首页 > 其它

LeetCode 101. Symmetric Tree

2018-03-04 22:05 399 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode