Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to parse the right view of python binary tree

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces you how to analyze the right view of the python binary tree, the content is very detailed, interested friends can refer to, hope to be helpful to you.

The right view of the binary tree

Topic description

Given a binary tree, imagine yourself standing on the right side of it, returning the node values you can see from the right in the order from top to bottom.

Example:

Input: [1, 2, 3, 5, 5, and 4]

Output: [1, 3, 4]

Explanation:

Train of thought analysis

Similar to the previous hierarchical traversal of the binary tree, this problem requires the use of queues

Create a queue

When traversing the nodes of each layer, store all the nodes of the next layer in the queue

Save the value of the last node of the new layer in the result before starting the traversal of the new layer node

Animation demonstration

GIF is a little slow to load in the animation. Please wait a moment ^ _ ^

Reference code 1class Solution {

2public:

3 vector rightSideView (TreeNode * root) {

4 vector res

5 if (! root) return res

6 queue q

7 q.push (root)

8 while (! q.empty ()) {

9 res.push_back (q.back ()-> val)

10 int size = q.size ()

11 for (int I = 0; I

< size; ++i) { 12 TreeNode *node = q.front(); 13 q.pop(); 14 if (node->

Left) q.push (node- > left)

15 if (node- > right) q.push (node- > right)

16}

17}

18 return res

19}

20}

Code screenshot

On how to parse the right view of the python binary tree is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report