描述
Given a binary tree, return the inorder traversal of its nodes’ values.
For example: Given binary tree {1,#,2,3}, 1
2 / 3 return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
分析
中序遍历,基本上沿用上一题 的框架。
Morris遍历继续参考这篇文章 。
代码
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class (object) : def inorderTraversalR (self, root, rs) : if not root: return self.inorderTraversalR(root.left, rs) rs.append(root.val) self.inorderTraversalR(root.right, rs) def inorderTraversal (self, root) : """ :type root: TreeNode :rtype: List[int] """ rs = [] self.inorderTraversalR(root, rs) return rs
迭代
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class (object) : def inorderTraversal (self, root) : """ :type root: TreeNode :rtype: List[int] """ rs = [] ss = [] cur = root while cur or ss: if cur: ss.append(cur) cur = cur.left else : cur = ss.pop() rs.append(cur.val) cur = cur.right return rs
Morris
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
class (object) : def inorderTraversal (self, root) : """ :type root: TreeNode :rtype: List[int] """ rs = [] cur = root while cur: if not cur.left: rs.append(cur.val) cur = cur.right else : node = cur.left while node.right and node.right != cur: node = node.right if not node.right: node.right = cur cur = cur.left else : node.right = None rs.append(cur.val) cur = cur.right return rs
近期评论