程式碼隨想錄演算法訓練營第十五天| 226. 翻轉二叉樹 101. 對稱二叉樹

jeasonGo發表於2024-03-20

226. 翻轉二叉樹
https://leetcode.cn/problems/invert-binary-tree/description/

public TreeNode invertTree(TreeNode root) {
        invert(root);
        return root;
    }
    public void invert(TreeNode node){
        if (node == null) return;
        TreeNode p = node.left;
        node.left = node.right;
        node.right = p;
        invert(node.left);
        invert(node.right);
    }

101. 對稱二叉樹
https://leetcode.cn/problems/symmetric-tree/description/

public boolean isSymmetric(TreeNode root) {
        return compare(root.left,root.right);
    }
    public boolean compare(TreeNode left,TreeNode right){
        if (left == null && right != null) return false;
        if (left != null && right == null) return false;
        if (left == null && right == null) return true;
        if (left.val != right.val) return false;
        boolean out = compare(left.left, right.right);
        boolean in = compare(left.right, right.left);
        return out && in;
    }

總結:本題只能用後序,因為要用到左右節點的資訊,先知道左右節點分別底下的對不對稱,再比這兩個節點對不對稱。 要不就用佇列迭代也行。

相關文章