您的位置:首页 > 其它

144. Binary Tree Preorder Traversal Stack version

2017-05-12 17:30 344 查看

原题

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?

代码实现

public IList<int> PreorderTraversal(TreeNode root)
{
IList<int> rtn = new List<int>();
if (root == null) return rtn;

Stack<TreeNode> s = new Stack<TreeNode>();
s.Push(root);
TreeNode tmp = root;
while (s.Count > 0)
{
if (tmp == null)
tmp = s.Peek();
rtn.Add(s.Peek().val);
s.Pop();
if(tmp.right!=null)
s.Push(tmp.right);
if (tmp.left != null)
s.Push(tmp.left);
tmp = tmp.left;
}
return rtn;
}


leetcode-solution库

leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: