LEETCODE —— Binary Tree的3 题 —— 3种非Recursive遍历
2014-11-19 14:39
423 查看
Binary Tree Preorder Traversal
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?
''' Created on Nov 19, 2014 @author: ScottGu<gu.kai.66@gmail.com, 150316990@qq.com> ''' # 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 postorderTraversal(self, root): visited={} stack=[] vals=[] if(root==None): return vals node=root stack.append(node) visited[node]=1 while(len(stack)!=0): node=stack[-1] if(node.left !=None and visited.has_key(node.left)==False): stack.append(node.left) visited[node.left]=1 continue else: if(node.right!=None and visited.has_key(node.right)==False): stack.append(node.right) visited[node.right]=1 continue node=stack.pop() if(node==None): continue vals.append(node.val) return vals
View Code
相关文章推荐
- LeetCode——111. Minimum Depth of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- LeetCode *** 104. Maximum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- LeetCode之Invert Binary Tree(Java版)
- [LeetCode]104. Maximum Depth of Binary Tree
- leetcode 75. Sort Colors 很不错的3种元素排序方法 + O(n)
- LeetCode 104. Maximum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- leetcode-111. Minimum Depth of Binary Tree
- Leetcode 654. Maximum Binary Tree 最大二叉树 解题报告
- 【Leetcode】543. Diameter of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- LeetCode 105,106. Construct Binary Tree 重建二叉树 Python Solution
- [leetcode]111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- Leetcode 543. Diameter of Binary Tree
- Leetcode 545. Boundary of Binary Tree
- 【leetcode】104. Maximum Depth of Binary Tree
- LeetCode543. Diameter of Binary Tree