226. 이진 트리 반전

설명:



이진 트리를 반전시킵니다.

해결책:



시간 복잡도 : O(n)
공간 복잡도: O(n)

// DFS approach
// In the recursion, you will traverse the tree until you hit to the bottom most leaf node
// The the right and left children of the current node will switch sides
// From the bottom going up, the ancestor nodes will switch their right and left child
// When we reach the root node, the tree will have been inverted
var invertTree = function(root) {
    // Stop when we reach a null value
    if(!root) return null;
    // Traverse the left side of the tree down to the leaf node
    const left = invertTree(root.left)
    // Traverse the right side of the tree down to the leaf node
    const right = invertTree(root.right)
    // Switch the placement of the children
    root.left = right
    root.right = left
    // Return the current node
    return root
};

좋은 웹페이지 즐겨찾기