LeetCode94 二叉树的中序遍历

链接: https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/

题意

给定一个二叉树的根节点 root ,返回它的 中序 遍历。

解法

递归写法很简单
着重复习下非递归写法
使用栈实现
如果一个节点没有左节点了,则它是当前最左的节点
把它指向它的右节点 进行下一次的迭代

代码

解法一

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
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<TreeNode*> stk;
vector<int> ret;
if (!root) return ret;
stk.push_back(root);
while(stk.size()) {
TreeNode* now = stk.back();
if (now -> left) {
stk.push_back(now -> left);
}
else {
ret.push_back(now -> val);
stk.pop_back();
while(stk.size() && now -> right == nullptr) {
now = stk.back();
stk.pop_back();
ret.push_back(now -> val);
}
if(now -> right)
stk.push_back(now -> right);
}
}
return ret;
}
};

解法二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<TreeNode*> stk;
vector<int> ret;
if (!root) return ret;
TreeNode* now = root;
while(stk.size() || now) {
while(now) {
stk.push_back(now);
now = now -> left;
}
TreeNode* temp = stk.back();
stk.pop_back();
ret.push_back(temp -> val);
now = temp -> right;
}
return ret;
}
};