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]
.
Note: Recursive solution is trivial, could you do it iteratively?
题目描述:
这是一个二叉树的先序遍历的题目,思路是直接用栈去实现。具体代码是借鉴的别人的,没怎么看懂,先把代码附上,以后慢慢体会。
代码实现:
/**
* 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>re;
const TreeNode *p;
stack<const TreeNode *>s;
p=root;
if(p!=NULL)
{
s.push(p);
}
while(!s.empty())
{
p=s.top();
s.pop();
re.push_back(p->val);
if(p->right!=NULL)
{
s.push(p->right);
}
if(p->left!=NULL)
{
s.push(p->left);
}
}
return re;
}
};