# Leetcode: Binary Tree Preorder Traversal（二叉树前序遍历）

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 binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
private:
vector<int> result;
public:
vector<int> preorderTraversal(TreeNode *root)
{
if (root)
{
result.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return result;
}
};```

```/**
* 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*> nodes;
vector<int> result;
TreeNode *node = root;
while (node || !nodes.empty())
{
//一路向右
if (node)
{
result.push_back(node->val);//先序遍历访问根节点
nodes.push(node);//节点入栈
node = node->left;
}
//右子树为空，追溯回最后的节点
else
{
node = nodes.top();
nodes.pop();//将此节点出栈
node = node->right;//指向此节点的右节点，将该节点当成根节点循环
}
}
return result;
}
};```

C#代码：

```/**
* Definition for binary tree
* public class TreeNode {
*     public int val;
*     public TreeNode left;
*     public TreeNode right;
*     public TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public IList<int> PreorderTraversal(TreeNode root)
{
IList<int> result = new List<int>();
Stack<TreeNode> nodes = new Stack<TreeNode>();
TreeNode node = root;
while (node != null || nodes.Count > 0)
{
if (node != null)
{
nodes.Push(node);
node = node.left;
}
else
{
node = nodes.Pop();
node = node.right;
}

}
return result;
}
}```

392 篇文章37 人订阅

0 条评论

27110

13330

14030

26210

10920

21810

12020

16530

14020

23230