Wednesday, August 5, 2015

199 - Binary Tree Right Side View

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.
For example:
Given the following binary tree,
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return [1, 3, 4].
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
Hide Tags
Tree Depth-first Search Breadth-first Search
Hide Similar Problems
(M) Populating Next Right Pointers in Each Node

从右向左 DFS,记录层数,如果超过已经完成的层数,就push当前节点的值进去。

/**
* 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 {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> rst;
        int done = 0;
        if(root)
            dfs(root, 1, done, rst);
        return rst;
    }
   
    void dfs(TreeNode* node, int level, int& done, vector<int>& rst)
    {
        if(level > done)
        {
            rst.push_back(node->val);
            done = level;
        }


        if(node->right)
            dfs(node->right, level+1, done, rst);


        if(node->left)
            dfs(node->left, level+1, done, rst);
    }
};

4 ms.

No comments:

Post a Comment