Thursday, June 23, 2016

199. Binary Tree Right Side View

First of all, my solution takes level-order traversal (BFS).

1:  class Solution {  
2:  public:  
3:    vector<int> rightSideView(TreeNode* root) {  
4:      vector<int> res;  
5:      vector<TreeNode*> cur;  
6:      if (root == NULL) return res;  
7:      cur.push_back(root);  
8:      while (!cur.empty()) {  
9:        vector<TreeNode*> next;  
10:        for (int i = 0; i < cur.size(); i++) {  
11:          if (cur[i]->left) next.push_back(cur[i]->left);  
12:          if (cur[i]->right) next.push_back(cur[i]->right);  
13:        }  
14:        res.push_back(cur[cur.size()-1]->val);  
15:        cur = next;  
16:      }  
17:      return res;  
18:    }  
19:  };  

Top voted uses DFS, i.e. traverse right child first and then left right. Save value only when current output size is less than level size.

1:  class Solution {  
2:  public:  
3:    vector<int> rightSideView(TreeNode* root) {  
4:      vector<int> res;  
5:      helper(root, 1, res);  
6:      return res;  
7:    }  
8:    void helper(TreeNode *root, int level, vector<int> &res) {  
9:      if (root == NULL) return;  
10:      if (res.size() < level) {  
11:        res.push_back(root->val);  
12:      }  
13:      helper(root->right, level+1, res);  
14:      helper(root->left, level+1, res);  
15:      return;  
16:    }  
17:  };  

No comments:

Post a Comment