Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie,
symmetric around its center).
思路:其中左子树和右子树对称的条件:
两个节点值相等,或者都为空
左节点的左子树和右节点的右子树对称
左节点的右子树和右节点的左子树对称
时间复杂度: 本质其实就是DFS,时间复杂度为O(n)
空间复杂度: O(h)
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return helper(root.left, root.right);
}
private boolean helper(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
if (left.val != right.val) {
return false;
}
return helper(left.left, right.right) && helper(left.right, right.left);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。