原题
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