mycode 95%
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] self.res = [] def inorder(root): if not root: return inorder(root.left) self.res.append(root.val) inorder(root.right) inorder(root) return self.res
参考:
重点是递归的理解:
大:先得到左子树的list,再加上root的val,再加上右子树的list
小:迭代,最小的tree也应该符合上述规则
class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == None: return [] left = self.inorderTraversal(root.left) right = self.inorderTraversal(root.right) left.append(root.val) left.extend(right) return left