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.

 

Analyse: the same as Binary Tree Level Order Traversal.

1. Recursion.

    Runtime: 4ms.

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> rightSideView(TreeNode *root) {
13         vector<int> result;
14         levelOrder(root, result, 0);
15         return result;
16     }
17     void levelOrder(TreeNode* root, vector<int>& result, int level){
18         if(!root) return;
19         if(level == result.size()) //the level does not exist and need to create it
20             result.push_back(0);
21         result[level] = root->val; //the recursion process ensures that the right most node value is added
22         
23         levelOrder(root->left, result, level + 1);
24         levelOrder(root->right, result, level + 1);
25     }
26 };

 

 

2. Iteration: When it reaches the end of the current level, push its value into the result vector.

  Runtime: 4ms.

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> rightSideView(TreeNode *root) {
13         vector<int> result;
14         if(!root) return result;
15         
16         queue<TreeNode* > qu;
17         qu.push(root);
18         //result.push_back(root->val);
19         while(!qu.empty()){
20             int n = qu.size();
21             while(n--){
22                 TreeNode* temp = qu.front();
23                 qu.pop();
24                 if(temp->left) qu.push(temp->left);
25                 if(temp->right) qu.push(temp->right);
26                 
27                 if(n == 0) result.push_back(temp->val);
28             }
29         }
30         return result;
31     }
32 };

 

posted @ 2015-08-02 23:06  amazingzoe  阅读(147)  评论(0编辑  收藏  举报