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);
    }
}

colorfuladventure
4 声望4 粉丝

引用和评论

0 条评论