您的位置:首页 > 其它

leetcode 题解:Binary Tree Preorder Traversal (二叉树的先序遍历)

2014-06-25 21:23 459 查看
题目:

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?

说明:

1)递归和非递归实现,其中非递归有两种方法

2)复杂度,时间O(n),空间O(n)

实现:

一、递归

/**
* Definition for binary tree
* 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) {
stack<TreeNode *> preorder_stack;
TreeNode *p=NULL;
vector<int> preorder_vec;
if(root==NULL) return preorder_vec;//若为空树,则返回空vector
preorder_stack.push(root);//当前节点入栈
while(!preorder_stack.empty())
{
p=preorder_stack.top();//栈顶节点出栈、输出
preorder_stack.pop();
preorder_vec.push_back(p->val);
//注意,下面入栈顺序不能错 ,因为先右后左,
//这样出栈时先遍历才是左孩子(左->中->右)
if(p->right)   preorder_stack.push(p->right);//若存在右孩子,则入栈
if(p->left)   preorder_stack.push(p->left);//若存在左孩子,则入栈
}
return preorder_vec;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐