Saturday, April 11, 2015

LeetCode [199] Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    vector<int> ret;
public:
    vector<int> rightSideView(TreeNode* root) {
        dfs(root, 0);
        return ret;
    }
    
    void dfs(TreeNode* node, int level){
        if(!node) return;
        if(ret.size()<level+1) ret.push_back(node->val);
        ret[level] = node->val;
        dfs(node->left, level+1);
        dfs(node->right, level+1);
    }
};

No comments:

Post a Comment