How to understand the hierarchical traversal of binary tree
This article is about how to understand the hierarchical traversal of binary tree. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it with the editor.
Algorithm:
The hierarchical traversal of the tree is one of the basic operations of the tree, including the hierarchical traversal of the binary tree, the hierarchical traversal of the multi-tree, the deformation of the hierarchical traversal of the binary tree, the hierarchical traversal + the flipping of the nodes of each layer and so on.
For this kind of problem, the typical algorithm is to store the tree in the array according to the hierarchy, and then uniformly process the data of each layer.
Topic 1:
one hundred and two。 Sequence traversal of binary tree
Code implementation:
/ * Definition for a binary tree node. * type TreeNode struct {* Val int * Left * TreeNode * Right * TreeNode *} * / / * method 1: non-recursive operation * / / * func levelOrder (root * TreeNode) [] [] int {if root = = nil {return nil} var stack [] * TreeNode var result [] [] int stack = append (stack,root) for {if len (stack) = = 0 {break } res,stack1: = helper (stack) if len (res)! = 0 {result = append (result,res)} stack = stack1} return result} func helper (stack [] * TreeNode) (res [] int, stackRes [] * TreeNode) {if len (stack) = = 0 {return} for ivy