Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3},
1 \ 2 / 3
return[1,2,3].
二叉树的前序遍历的递归实现C++:
class Solution {
public:
void preorder(TreeNode* root, vector<int> &path)
{
if(root!=NULL)
{
path.push_back(root->val);
preorder(root->left, path);
preorder(root->right, path);
}
}
vector<int> preorderTraversal(TreeNode *root) {
vector<int> path;
preorder(root, path);
return path;
}
};
二叉树的前序遍历的非递归实现C++:
第一种写法
<span style="font-size:18px;">class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> path;
stack<TreeNode*> stk;
if(root != NULL)
{
stk.push(root);
while(!stk.empty())
{
root = stk.top();
stk.pop();
path.push_back(root->val);
if(root->right) stk.push(root->right);
if(root->left) stk.push(root->left);
}
}
return path;
}
};</span>
第二种写法:
<span style="font-size:18px;">class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> path;
stack<TreeNode*> stk;
while(root != NULL || !stk.empty())
{
if(root != NULL)//走到最左
{
while(root)
{
path.push_back(root->val);
stk.push(root);
root = root->left;
}
}else//root为NULL,说明走到最左的节点
{
root = stk.top()->right;
stk.pop();
}
}
return path;
}
};</span>