# 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] """ res = [] self.helper(root, res) return res def helper(self, root, res): if root: self.helper(root.left, res) res.append(root.val) self.helper(root.right, res)
#非递归方法
class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] stack = [] while True: while root: stack.append(root) root = root.left if not stack: return res node = stack.pop() res.append(node.val) root = node.right return res
def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] stack = [] while True: while root: stack.append(root) root = root.left if not stack: return res node = stack.pop() res.append(node.val) root = node.right return res