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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
|
class Solution: def preOrd(self, root: TreeNode) -> List[int]: res = [] stack = [(0, root)] while stack: flag, cur = stack.pop() if not cur: continue if flag == 0: stack.append((0, cur.right)) stack.append((0, cur.left)) stack.append((1, cur)) else: res.append(cur.val) return res
class Solution: def inOrd(self, root: TreeNode) -> List[int]: res = [] cur = root
while cur: if not cur.left: res.append(cur.val) cur = cur.right else: pre = cur.left while pre.right and pre.right != cur: pre = pre.right if not pre.right: pre.right = cur cur = cur.left else: pre.right = None res.append(cur.val) cur = cur.right return res
class Solution: def preorder(self, root: 'Node') -> List[int]: if not root: return [] res = [root.val] for node in root.children: res.extend(self.preorder(node)) return res
class Solution: def preorder(self, root: 'Node') -> List[int]: res = [] def helper(root): if not root: return res.append(root.val) for child in root.children: helper(child) helper(root) return res
class Solution: def preorder(self, root: 'Node') -> List[int]: if not root: return [] s = [root] res = [] while s: node = s.pop() res.append(node.val) s.extend(node.children[::-1]) return res
|