Skip to content

Commit 47d2f44

Browse files
dyhdyh
authored andcommitted
添加树的遍历
1 parent 9624be0 commit 47d2f44

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
}

python/treenode/inorder_treenode.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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

0 commit comments

Comments
 (0)