Leetcode: Binary Tree Right Side View

Source: Internet
Author: User

Leetcode: Binary Tree Right Side View

I. Question

Let's give you a binary tree. Assume that a few are standing behind the tree, then you can only see the rightmost node.

For example:

1 <---

/\

2 3 <---

\\

5 4 <---

The return value is [1, 3, 4].

Ii. Analysis

We usually use DFS or BFS for tree traversal. This topic is actually traversal. However, we only need to record the rightmost node of each row. My first thought was to access only the right node each time. But when I thought about it carefully, not all of them were in this situation. For example, the rightmost node may be in the left half. I immediately dismissed this idea and thought that we had to traverse all the nodes in any case. However, we had to traverse the nodes in a forward order in disguised form, that is, the order of the current node-Right node-left node, they are put into the queue every time, but we only need to record the first node, and all others are released.

 

 

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:        vector
 
   rightSideView(TreeNode *root) {        vector
  
    res;        if(root == NULL)            return res;        queue
   
     nQueue;        TreeNode *node = root;        nQueue.push(node);        while(!nQueue.empty()){            int size = nQueue.size();            for(int i = 0; i < size; i++){                node = nQueue.front();                nQueue.pop();                if(i == 0)                    res.push_back(node->val);                if(node->right)                    nQueue.push(node->right);                if(node->left)                    nQueue.push(node->left);            }        }        return res;    }};
   
  
 


 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.