Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode_199_Binary Tree Right Side View #11

Open
lihe opened this issue Nov 1, 2019 · 0 comments
Open

Leetcode_199_Binary Tree Right Side View #11

lihe opened this issue Nov 1, 2019 · 0 comments
Labels

Comments

@lihe
Copy link
Owner

lihe commented Nov 1, 2019

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       <---

题意:这题就是求二叉树每层的最右边的节点。

算法思路:

  1. 层序遍历时,将节点与层数绑定为pair,压入队列中;
  2. 将每层的最后一个节点压入到view中。
class Solution{
public:
    std::vector<int> rightSideView(TreeNode* root){
        std::vector<int> view;
        std::queue<std::pair<TreeNode*, int>> Q;
        if(root){
            Q.push(std::make_pair(root, 0));
        }
        while(!Q.empty()){
            TreeNode* node = Q.front().first;
            int depth = Q.front().second;
            Q.pop();
            if(view.size() == depth){
                view.push_back(node -> val);
            }
            else{
                view[depth] = node -> val;
            }
            if(node -> left){
                Q.push(std::make_pair(node -> left, depth + 1));
            }
            if(node -> right){
                Q.push(std::make_pair(node -> right, depth + 1));
            }
        }
        return view;
    }
};
@lihe lihe changed the title Binary Tree Right Side View Leetcode_199_Binary Tree Right Side View Nov 1, 2019
@lihe lihe added the Leetcode label Nov 1, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant