[LeetCode]94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
题意:中序遍历树
先写一种比较蠢的方法,我可以借口对python的数据结构不熟悉
1 class Solution(object): 2 def inorderTraversal(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: List[int] 6 """ 7 res = [] 8 if root != None: 9 if root.left!=None: 10 for i in self.inorderTraversal(root.left): 11 res.append(i) 12 res.append(root.val) 13 if root.right!=None: 14 for i in self.inorderTraversal(root.right): 15 res.append(i) 16 return res
一种正常的写法:
1 class Solution(object): 2 def inorderTraversal(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: List[int] 6 """ 7 res = [] 8 self.helper(root,res) 9 return res 10 11 12 def helper(self,root,res): 13 if root: 14 self.helper(root.left,res) 15 res.append(root.val) 16 self.helper(root.right,
上面两种方法都使用了递归,下面一种未使用递归的方法:
1 class Solution(object): 2 def inorderTraversal(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: List[int] 6 """ 7 res,s = [],[] 8 while True: 9 while root: 10 s.append(root) 11 root = root.left 12 if not s: 13 return res 14 node = s.pop() 15 res.append(node.val) 16 root=node.right
顺便吐槽一句:为什么把这个题分到哈希类???!!!