Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to analyze the hierarchical traversal of python binary tree

Shulou Source: shulou.com Published: 2022-06-01 14:15:04 10月03日 Update

This article shows you how to analyze python binary tree level traversal, concise and easy to understand, absolutely can make your eyes shine, through the detailed introduction of this article I hope you can gain something.

Binary tree classification

107. Hierarchical Traversals of Binary Trees II

topic

Given a binary tree, returns a bottom-up hierarchical traversal of its node values. (i.e. traverse layer by layer from left to right from the layer where the leaf node is located to the layer where the root node is located)

For example:

Given binary tree [3,9,20,null,null,15,7]

3 / \ 9 20 / \ 15 7

Returns its bottom-up hierarchical traversal as:

[ [15,7], [9,20], [3]] Thought breadth first search

Hierarchical traversal of trees can be achieved using breadth-first search. Search from the root node, traverse all nodes of the same level at a time, and store node values for that level using a list

If you want to output node values for each level from top to bottom, it is intuitive to add a list of node values for that level to the end of the result list after traversing a level of nodes. This problem requires output of node values for each level from bottom to top, with a slight modification: After traversing a level of nodes, add a list of node values for that level to the head of the result list

code/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public List levelOrderBottom(TreeNode root) { //Results List levelOrder = new LinkedList(); if(root == null){ return levelOrder; } Queue queue = new LinkedList(); queue.offer(root); //breadth search while(! queue.isEmpty()){ List level = new ArrayList(); int size = queue.size(); for(int i = 0; i < size; i++){ TreeNode node = queue.poll(); level.add(node.val); if(node.left != null){ queue.offer(node.left); } if(node.right != null){ queue.offer(node.right); } } //insert to the first position every time levelOrder.add(0,level); } return levelOrder; }} The above content is how to analyze the hierarchical traversal of python binary tree. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserves, please pay attention to the industry information channel.

Tags: Nodes hierarchy search breadth results storage analysis content location skills knowledge output concise intuitive concise code location practices leaves head Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple MySQL OPPO Reno Huawei vpn