-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path94-InorderTraversal.py
More file actions
111 lines (94 loc) · 2.68 KB
/
94-InorderTraversal.py
File metadata and controls
111 lines (94 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# Python3 递归 时间复杂度:O(n) 空间复杂度:O(n)
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val = 0, left = None, right = None):
self.val = val
self.left = left
self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
def inorder(root, res):
if root == None:
return
inorder(root.left, res)
res.append(root.val)
inorder(root.right, res)
res = []
inorder(root, res)
return res
# C++ 递归
class Solution {
public:
void inorder(TreeNode* root, vector<int>& res) {
if (!root) { // 遇到空节点返回
return;
}
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root, res);
return res;
}
};
# Java 递归
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
inorder(root, res);
return res;
}
public void inorder(TreeNode root, list<Integer> res) {
if (root == null) {
return;
}
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
}
# Python3 迭代
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
stk = []
while root != None or stk != []:
while root != None:
stk.append(root)
root = root.left
root = stk[-1]
stk.pop()
res.append(root.val)
root = root.right
return res
# C++ 迭代
# 递归与迭代两种方式是等价的,区别在于递归隐式地维护了一个栈,
# 迭代需要显示模拟这个栈
struct TreeNode {
int val;
TreeNode *left;
TreeNode * right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
while (root != nullptr || !stk.empty()) {
while (root != nullptr) {
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
};