Invert Binary Tree: Recursive Solution

Jay·2022년 5월 16일
0

Grind 120

목록 보기
6/38


First Thoughts: binary tree is inherently recursive. inverting left and right subtrees recursively will eventually result in inverting the whole tree.

My Solution:

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root==null) return null;
        TreeNode leftInverted = invertTree(root.right);
        TreeNode rightInverted = invertTree(root.left);
        TreeNode inverted = new TreeNode(root.val, leftInverted, rightInverted);
        return inverted;
    }
}

Catch Point

  1. Binary Trees are tightly related to recursion. Helpful to think of solutions in bulk (inverted left subtree, inverted right subtree)

0개의 댓글