美文网首页
leetcode 226. Invert Binary Tree

leetcode 226. Invert Binary Tree

作者: 咿呀咿呀呦__ | 来源:发表于2017-12-28 10:56 被阅读0次

Invert a binary tree.

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

to

     4
   /   \
  7     2
 / \   / \
9   6 3   1
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        invert = self.invertTree
        if root:  
            root.left, root.right = invert(root.right), invert(root.left)
            return root
        return None

And an iterative version using my own stack:

def invertTree(self, root):
    stack = [root]
    while stack:
        node = stack.pop()
        if node:
            node.left, node.right = node.right, node.left
            stack += node.left, node.right
    return root

Complexity Analysis:

Since each node in the tree is visited only once, the time complexity is O(n), where n is the number of nodes in the tree. We cannot do better than that, since at the very least we have to visit each node to invert it.

Because of recursion, O(h) function calls will be placed on the stack in the worst case, where h is the height of the tree. Because h∈O(n), the space complexity is O(n).

Complexity Analysis:

Since each node in the tree is visited / added to the queue only once, the time complexity is O(n), where n is the number of nodes in the tree.

Space complexity is O(n), since in the worst case, the queue will contain all nodes in one level of the binary tree. For a full binary tree, the leaf level has ⌈n/2⌉=O(n) leaves.

相关文章

网友评论

      本文标题:leetcode 226. Invert Binary Tree

      本文链接:https://www.haomeiwen.com/subject/sppmgxtx.html