LintCode-66.二叉树的前序遍历

时间:2022-08-20 06:56:12

二叉树的前序遍历

给出一棵二叉树,返回其节点值的前序遍历。

样例

给出一棵二叉树 {1,#,2,3},

LintCode-66.二叉树的前序遍历

返回 [1,2,3].

挑战

你能使用非递归实现么?

标签

递归 二叉树 二叉树遍历 非递归

code

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/ class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector<int> preorderTraversal(TreeNode *root) {
// write your code here
vector<int> order;
if(root == NULL)
return order; stack<TreeNode*> s;
TreeNode *p=root;
while(p!=NULL||!s.empty()) {
while(p!=NULL) {
order.push_back(p->val);
s.push(p);
p=p->left;
}
if(!s.empty()) {
p=s.top();
s.pop();
p=p->right;
}
}
return order;
}
};