您的位置:首页 > 其它

[LeetCode] Binary Tree Preorder Traversal 二叉树的先序遍历

2014-12-05 16:29 405 查看
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?

一般我们提到树的遍历,最常见的有先序遍历,中序遍历,后序遍历和层序遍历,它们用递归实现起来都非常的简单。而题目的要求是不能使用递归求解,于是只能考虑到用非递归的方法,这就要用到stack来辅助运算。由于先序遍历的顺序是"根-左-右", 算法为:

1. 把根节点push到栈中

2. 循环检测栈是否为空,若不空,则取出栈顶元素,保存其值,然后看其右子节点是否存在,若存在则push到栈中。再看其左子节点,若存在,则push到栈中。

代码如下:

/**
* 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) {
vector<int> res;
stack<TreeNode*> s;
if (!root) return res;
s.push(root);
while (!s.empty()) {
TreeNode *p = s.top();
res.push_back(p->val);
s.pop();
if (p->right) s.push(p->right);
if (p->left) s.push(p->left);
}
return res;
}
};


LeetCode All in One 题目讲解汇总(持续更新中...)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐