树的遍历 | 翻转二叉树

Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

思路1 递归:

把左子树和右子树进行交换。交换完之后,再去递归翻转左子树和右子树

class Solution(object):
    def invertTree(self, root):
            if root:
                root.left,root.right = root.right,root.left
                self.invertTree(root.left)
                self.invertTree(root.right)
            return root

思路2 遍历

换父节点的时候,把子节点存下来,然后换完父节点了,就去换子点的。

class Solution(object):
    def invertTree(self, root):
        node = root
        queue = [root]
        while len(queue):
            root = queue.pop(-1)
            if root:
                root.left,root.right = root.right,root.left
                if root.left:
                    queue.append(root.left)
                if root.right:
                    queue.append(root.right)
        return node

猜你喜欢

转载自www.cnblogs.com/xmxj0707/p/10381201.html