[Leetcode Binary Tree Series] 1 In-order traversal of binary tree

13b4ed2033510c3dc7d313034c4f0993.gif


 This article involves knowledge points 

  • The basic concept of binary tree

  • Stack usage

The basic concepts of the binary tree and the related concepts of the stack have been introduced before, and the forgotten friends will definitely double the effect after reviewing!

Review of Binomial Tree Knowledge: [ Today, add a BGM to the Binomial Tree, the Binomial Tree is singing! ]

Stack knowledge review: [leetcode stack queue] 1 Stack implementation queue

1Leetcode94 In-order traversal of binary tree

Given a binary tree, return its mid-order  traversal.





Example 1:

 [1,null,2,3]
   1
    \
     2
    /
   3 [1,3,2]




Xiaolan hopes everyone will think about it for 1 minute

The effect is better!

0 1 Question analysis
  • Ideas

The basic idea

For a binary tree, we can get the root pointer of the root node, the first to visit is the root node. But we need to output in the order of the left subtree, the root node, and the right subtree, so what data structure has the characteristics of appearing first, which introduces the stack .


  • Visit from the root node, visit its left node in turn, and stack.

759f1cba8ef9f15600869dffc17d10a8.png

  • If it is NULL, pop the top element of the stack and put the right node of this element on the stack, repeat this step. As shown in the figure above, D has no left and right nodes, and the top D and B of the stack are popped up. At this time, if there is a right node in B, it will be pushed into the stack as shown in the figure below.

b224470ec8f27097dc3a0e987672da92.png



02 code implementation

1c++ version

dc6f7781e18d161a678e815d593d5a2c.jpeg

2python version

dfc7e331da8c136126345a2f26e7395c.jpeg

3java version

fc7f546b42f261208c40e3fb6baaec7d.jpeg


Guess you like

Origin blog.51cto.com/14984904/2545484