Leetcode 226 Invert Binary Tree

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
posted @ 2015-06-12 16:15  lilixu  阅读(142)  评论(0编辑  收藏  举报