Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to parse the right view of python binary tree

Shulou Source: shulou.com Published: 2022-06-01 14:14:30 10月31日 Update

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.

Tags: Nodes views code content animation right more references help presentations good interests guys partners levels ideas screenshots articles knowledge examples Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Docker Microsoft Shulou Technology Xiaomi