Leetcode 226 Invert Binary Tree

1493 단어 LeetCode
Invert a binary tree.
     4

   /   \

  2     7

 / \   / \

1   3 6   9

to
     4

   /   \

  7     2

 / \   / \

9   6 3   1

차례로 실현되다
def invert_tree(root)

    root.right, root.left = invert_tree(root.left), invert_tree(root.right) if root

    root

end

순환 실현
def invert_tree(root)

  return if not root

  stack = [root]

  while not stack.empty?

    if node = stack.pop

        node.left, node.right = node.right, node.left

        stack << node.left << node.right

    end

  end

  root

end

좋은 웹페이지 즐겨찾기