第六章 二叉树 part02

57 阅读1分钟

226. Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.

题目解析:

  • 翻转就是交换左右两个节点的位置,可以使用递归

代码:

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root != null) {
            TreeNode temp = root.left;
            root.left = invertTree(root.right);
            root.right = invertTree(temp);
        }
        return root;
    }
}

101. Symmetric Tree

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

题目解析:

  • 对称不是比较父节点的左右节点,而是整棵树左右对称的位置,也可以使用递推

代码:

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return symmetric(root.left, root.right);
    }

    public boolean symmetric(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        }
        if (left == null && right != null || left != null && right == null) {
            return false;
        }
        return left.val == right.val &&
            symmetric(left.right, right.left) && symmetric(left.left, right.right);
    }
}