Tuesday, August 25, 2015

Leetcode 199. Binary Tree Right Side View

https://leetcode.com/problems/binary-tree-right-side-view/

The lazy way is to get level order and use the right most element, while it is wasteful. We can do better than that. The key is to put right nodes in if exist.

Solution:
# T:O(n) S:O(h)
class Solution:
    # @param root, a tree node
    # @return a list of integers
    def rightSideView(self, root):
        result = []
        self.rightSideViewDFS(root, 1, result)
        return result
    
    def rightSideViewDFS(self, node, depth, result):
        if not node:
            return
        
        if depth > len(result):
            result.append(node.val)
        
        self.rightSideViewDFS(node.right, depth+1, result)
        self.rightSideViewDFS(node.left, depth+1, result)
Run Time: 60 ms

No comments:

Post a Comment