144. 二叉树的前序遍历
早些的学习笔记在这里:[二叉树中序遍历](./94. 二叉树的中序遍历/)。
本文件只记录该题的解题思路和代码:
先上代码:
- 迭代代码
1 | /** |
思路:
前序遍历的方法,对于每个节点来说都是如下:
- 到达当前节点,输出当前节点值,记录当前节点(后续还要搜索右子节点)
- 向左寻找左子节点,存在则将当前节点更新为左子节点;不存在则更新为右子节点
- 由于右子节点也可能不存在,此时针对到达新的节点时,此节点为空的情况,需要出栈前驱节点,并将当前节点更新为前驱节点的右子节点
相应代码如下:
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 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> stk;//栈中存放右子节点未处理的根节点
auto cur = root;
while(!(stk.empty() && cur==nullptr)){
if(!cur){
cur = stk.top()->right;
stk.pop();
continue;
}
ans.emplace_back(cur->val);
if(cur->left){
stk.push(cur);
cur = cur->left;
}
else cur = cur->right;
}
return ans;
}
};