【LEETCODE OJ】Binary Tree Preorder Traversal
2014-04-04 02:03
330 查看
Problem Link:
http://oj.leetcode.com/problems/binary-tree-preorder-traversal/
Even iterative solution is easy, just use a stack storing the nodes not visited. Each iteration, pop a node and visited it, then push its right child and then left child into stack if possible.
Note the special case that the root is NULL.
The python code is as follows, which is accepted by OJ.leetcode.
http://oj.leetcode.com/problems/binary-tree-preorder-traversal/
Even iterative solution is easy, just use a stack storing the nodes not visited. Each iteration, pop a node and visited it, then push its right child and then left child into stack if possible.
Note the special case that the root is NULL.
The python code is as follows, which is accepted by OJ.leetcode.
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of integers def preorderTraversal(self, root): """ Iterative way using a stack, hope no LTE... """ res = [] non_visited = [] if root is not None: non_visited.append(root) while non_visited: top = non_visited.pop() res.append(top.val) if top.right: non_visited.append(top.right) if top.left: non_visited.append(top.left) return res
相关文章推荐
- [LeetCode OJ]Binary Tree Preorder Traversal
- LeetCode OJ:Binary Tree Preorder Traversal(前序遍历二叉树)
- LeetCode OJ - Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal
- 【LeetCode OJ】Binary Tree Preorder Traversal
- LeetCode OJ:Binary Tree Preorder Traversal
- LeetCode OJ - Binary Tree Preorder Traversal
- LeetCode OJ 之 Binary Tree Preorder Traversal (二叉树的前序遍历)
- [LeetCode OJ] Binary Tree Preorder Traversal 解题报告
- LeetCode OJ --问题与解答 Binary Tree Preorder Traversal
- LeetCode OJ --问题与解答 Binary Tree Preorder Traversal
- leetcode OJ -Binary Tree Preorder Traversal(2014.1.20)
- LeetCode OJ:Construct Binary Tree from Preorder and Inorder Traversal(从前序以及中序遍历结果中构造二叉树)
- LeetCode OJ - Binary Tree Preorder Traversal
- LeetCode OJ:Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode OJ--Binary Tree Preorder Traversal
- 【LeetCode OJ】Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]144 Binary Tree Preorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal