左根右;递归或显式栈模拟递归。
OJ: leetcodecn
题目 ID: binary-tree-inorder-traversal
难度:入门
标签:二叉树栈递归cpppython
日期: 2026-07-28 22:05
题意
返回二叉树中序遍历的节点值序列。
思路
递归:左-根-右。迭代:显式栈模拟递归,先把左链全部入栈,弹出访问后转向右子树。
代码
cpp
/**
* Author by Rainboy
*/
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> ans;
stack<TreeNode *> st;
auto cur = root;
while (cur || !st.empty()) {
while (cur) {
st.push(cur);
cur = cur->left;
}
cur = st.top();
st.pop();
ans.push_back(cur->val);
cur = cur->right;
}
return ans;
}
};
TreeNode *build(istream &in, int n) {
if (!n)
return nullptr;
vector<TreeNode *> nodes(n);
for (int i = 0, v; i < n; i++) {
in >> v;
if (v != -1)
nodes[i] = new TreeNode(v);
}
for (int i = 0; i < n; i++) {
if (!nodes[i])
continue;
int l = 2 * i + 1, r = 2 * i + 2;
if (l < n)
nodes[i]->left = nodes[l];
if (r < n)
nodes[i]->right = nodes[r];
}
return nodes[0];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
auto root = build(cin, n);
auto v = Solution().inorderTraversal(root);
for (int x : v)
cout << x << ' ';
return 0;
}python
#!/usr/bin/env python3
from typing import List, Optional
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans, stack = [], []
cur = root
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
ans.append(cur.val)
cur = cur.right
return ans
def build(arr):
if not arr:
return None
nodes = [TreeNode(v) if v != -1 else None for v in arr]
for i in range(len(nodes)):
if nodes[i] is None:
continue
l, r = 2 * i + 1, 2 * i + 2
if l < len(nodes):
nodes[i].left = nodes[l]
if r < len(nodes):
nodes[i].right = nodes[r]
return nodes[0]
def main() -> None:
n = int(input())
a = list(map(int, input().split()))
root = build(a)
print(*Solution().inorderTraversal(root))
if __name__ == "__main__":
main()复杂度
- 时间复杂度:O(n)。
- 空间复杂度:O(n) 递归栈/显式栈。
总结
中序迭代栈是"沿左链入栈 → 弹出访问 → 转向右子树"三部曲,是后续很多树操作的基础。