File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
java/java_test/src/treenode Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ package treenode ;
2
+
3
+ import common .TreeNode ;
4
+
5
+ import java .util .ArrayList ;
6
+ import java .util .List ;
7
+ import java .util .Stack ;
8
+
9
+ /**
10
+ * @author dengyh
11
+ * @version 1.0
12
+ * @date 2024/12/1 19:26
13
+ * @description 中序
14
+ */
15
+ public class InOrder {
16
+ public List <Integer > inorderTraversal (TreeNode root ){
17
+ List <Integer > res = new ArrayList <>();
18
+ inorder (root , res );
19
+ return res ;
20
+ }
21
+
22
+ public void inorder (TreeNode root , List <Integer > res ) {
23
+ if (root == null ) return ;
24
+ Stack <TreeNode > stack = new Stack <>();
25
+ TreeNode cur = root ;
26
+ while (cur != null || !stack .isEmpty ()){
27
+ while (cur != null ){
28
+ stack .push (cur );
29
+ cur = cur .left ;
30
+ }
31
+ if (!stack .isEmpty ()){
32
+ cur = stack .pop ();
33
+ res .add (cur .val );
34
+ cur = cur .right ;
35
+ }
36
+ }
37
+ }
38
+ }
Original file line number Diff line number Diff line change
1
+ from typing import Optional , List
2
+
3
+ from listnode .TreeNode import TreeNode
4
+
5
+
6
+ def inorderTraversal (self , root : Optional [TreeNode ]) -> List [int ]:
7
+ res = []
8
+ stack = []
9
+ cur = root
10
+ while cur or stack :
11
+ while cur :
12
+ stack .append (cur )
13
+ cur = cur .left
14
+ cur = stack .pop ()
15
+ res .append (cur .data )
16
+ cur = cur .right
17
+ return res
You can’t perform that action at this time.
0 commit comments