1. 程式人生 > >#Leetcode# 199. Binary Tree Right Side View

#Leetcode# 199. Binary Tree Right Side View

https://leetcode.com/problems/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       <---

程式碼:

/**
 * 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<vector<int> > levelOrder;
        vector<int> ans;
        if(!root) return ans;
        
        queue<pair<TreeNode*, int>> q;
        q.push(make_pair(root, 1));
        while(!q.empty()) {
            pair<TreeNode*, int> tp = q.front();
            q.pop();
            
            if(tp.second > levelOrder.size()) {
                vector<int> v;
                levelOrder.push_back(v);
            }
            
            levelOrder[tp.second - 1].push_back(tp.first->val);
            
            if(tp.first->left) 
                q.push(make_pair(tp.first->left, tp.second + 1));
            
            if(tp.first->right) 
                q.push(make_pair(tp.first->right, tp.second + 1));
        }
        
        
        for(int i = 0; i < levelOrder.size(); i ++) {
            ans.push_back(levelOrder[i][levelOrder[i].size() - 1]);
        }
        
        return ans;
    }
    
};

  FH 寫的 bfs 

程式碼:

/**
 * 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<vector<int> > levelOrder;
        vector<int> ans;
        if(!root) return ans;
        
        helper(root, levelOrder, 1);
        
        for(int i = 0; i < levelOrder.size(); i ++) {
            ans.push_back(levelOrder[i][levelOrder[i].size() - 1]);
        }
        
        return ans;
    }
    void helper(TreeNode* root, vector<vector<int> >& ans, int depth) {
      vector<int> v;
      if(depth > ans.size()) {
        ans.push_back(v);
        v.clear();
      }
      ans[depth - 1].push_back(root -> val);
      if(root -> left)
        helper(root -> left, ans, depth + 1);
      if(root -> right)
        helper(root -> right, ans, depth + 1);
    }
};

  小張寫的 code  感覺一晚上都在看層序遍歷