LeetCode 144. Binary Tree Preorder Traversal
Solution1:递归版
二叉树的前序遍历递归版是很简单的,关键是迭代版的代码既难理解又难写!
迭代版链接:https://blog.csdn.net/allenlzcoder/article/details/79837841
/**
* 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> res;
my_Pretraversal(root, res);
return res;
}
void my_Pretraversal(TreeNode* root, vector<int>& res) {
if (!root) return;
res.push_back(root->val);
my_Pretraversal(root->left, res);
my_Pretraversal(root->right, res);
}
};
Solution2:迭代版
前序遍历也是最简单的一种,分为下面三个步骤:
1. 申请一个栈,将头结点压入栈
2. 弹出栈顶指针,记作:cur,如果这个这个指针有右孩子,将右孩子入栈,如果有左孩子,将左孩子入栈;
3. 不断重复过程2,直到栈为空,结束程序!
/**
* 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> res;
if (!root) return res;
stack<TreeNode*> my_stack;
my_stack.push(root);
while(!my_stack.empty()) {
TreeNode* cur = my_stack.top();
my_stack.pop();
res.push_back(cur->val);
if(cur->right != NULL) my_stack.push(cur->right);
if(cur->left != NULL) my_stack.push(cur->left);
}
return res;
}
};