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相关文章推荐
- 144. Binary Tree Preorder Traversal
- LeetCode(144):Binary Tree Preorder Traversal
- leetcode 144 Binary Tree Preorder Traversal C++
- Binary Tree Preorder Traversal (leetcode 144)
- LeetCode(144) Binary Tree Preorder Traversal
- Leetcode #144 Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- LeetCode 144 Binary Tree Preorder Traversal
- LeetCode 144: Binary Tree Preorder Traversal
- [leetcode 144]Binary Tree Preorder Traversal
- Leetcode144: Construct Binary Tree from Preorder and Inorder Traversal
- 144. Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- Stack的应用——Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- leetcode 144 —— Binary Tree Preorder Traversal
- LeetCode: Binary Tree Preorder Traversal [144]
- 144. Binary Tree Preorder Traversal
- LC144 Binary Tree Preorder Traversal
- 【LEETCODE】144-Binary Tree Preorder Traversal