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.

For example:
Given the following binary tree,

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return [1, 3, 4].

深搜

vector<int> rightSideView(TreeNode* root) {
    vector<int> v;
    dfs(root, 1, v);
    return v;
}

void dfs(TreeNode* root, int i, vector<int>& v){
    if(root == NULL) return;
    
    //最先到i层的是最右边的
    if(i > v.size()) {
        v.push_back(root->val);
    }
    
    //先搜索右子树
    dfs(root->right, i + 1, v);
    dfs(root->left, i + 1, v);
}

广搜

vector<int> rightSideView(TreeNode* root) {
    vector<int> result;
    if(root == NULL) return result;
    
    queue<TreeNode*> q;
    q.push(root);
    TreeNode* node;
    while(!q.empty()){
        //记录当前层有多少个点
        int size = q.size();
        for(int i = 0; i < size; i++){
            node = q.front();
            q.pop();
            if(i == size - 1) result.push_back(node->val);
            if(node->left) q.push(node->left);
            if(node->right) q.push(node->right);
        }
    }
    return result;
    
}

你可能感兴趣的:(199. Binary Tree Right Side View)