Skip to content

Latest commit

ย 

History

History
91 lines (80 loc) ยท 2.21 KB

File metadata and controls

91 lines (80 loc) ยท 2.21 KB

Intuition

Use DFS, referencing the property of a tree (i.e. child node is the root node of a subtree.)

Approach

  1. Visit the root node.
  2. If visited node is nil, return nil
  3. Swap left and right nodes.
  4. Visit Swapped left and right nodes.
  5. Repeat Step 2 ~ 4.

Complexity

  • Time complexity: $$O(n)$$
  • Space complexity: $$O(n)$$

Code

func invertTree(root *TreeNode) *TreeNode {
    if root == nil {
        return nil
    }
    root.Left, root.Right = invertTree(root.Right), invertTree(root.Left)
    return root
}

Intuition

Visit, But Use BFS. (for loop)

Approach

  1. Create Queue and push root node to it.
  2. If the queue is empty, return the root node.
  3. Otherwise, pop the top node.
  4. Swap the left and right children of the removed node.
  5. Push swapped children.
  6. Repeat Step

Complexity

  • Time complexity: $$O(n)$$
  • Space complexity: $$O(n)$$

Code

type Queue[T any] struct {
    Index int
    Nodes []T
}

func NewQueue[T any]() Queue[T] {
    return Queue[T]{Nodes: make([]T, 0)}
}

func (q *Queue[T]) Push(node T) {
    q.Nodes = append(q.Nodes, node)    
}

func (q *Queue[T]) Pop() T {
    ret := q.Nodes[q.Index]
    q.Index++
    return ret
}

func (q *Queue[T]) IsEmpty() bool {
    return q.Index == len(q.Nodes)
}

func invertTree(root *TreeNode) *TreeNode {
    q := NewQueue[*TreeNode]()
    q.Push(root)
    for !q.IsEmpty() {
        t := q.Pop()
        if t == nil {
            continue
        }
        t.Left, t.Right = t.Right, t.Left
        
        q.Push(t.Left)
        q.Push(t.Right)
    }
    return root
}

Learned

  • ๊ณ ์–ธ์–ด์—์„œ a, b = b, a ์ฒ˜๋Ÿผ ๊ฐ„๊ฒฐํ•œ ์ฝ”๋”ฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
  • ํฌ์ธํ„ฐ ํƒ€์ž…๊ณผ ์ผ๋ฐ˜ ํƒ€์ž…์˜ ์ฐจ์ด (๊ณ ์–ธ์–ด์—์„œ๋Š” ์ผ๋ฐ˜ ํƒ€์ž…์„ ๋„˜๊ธธ ์‹œ ๋ฌด์กฐ๊ฑด ๋ณต์‚ฌํ•œ๋‹ค.)