result = [] stack = [] curr = root while stack or curr: # 能左就左,否则向右一步 while curr: stack.append(curr) curr = curr.left if curr.left else curr.right # pop stack,添加到结果 curr = stack.pop() result.append(curr.val) # 栈不空且当前节点是栈顶的左子节点,转到其右兄弟,否则退栈 if stack and stack[-1].left == curr: curr = stack[-1].right else: curr = None return result if __name__ == '__main__': from tools import Tree tree = Tree() tree.construct_tree([1, -1, 11, -2, -3, 21, 6, None, None, None, 5]) results = tree.post_order_traversal() print(results) print(Solution0().postorderTraversal(tree.root))
q.append(node.left) if node.right: q.append(node.right) if not node.left or not node.right: self.deque.append(node) def insert(self, v): """ :type v: int :rtype: int """ parent = self.deque[0] self.deque.append(TreeNode(v)) if not parent.left: parent.left = self.deque[-1] else: parent.right = self.deque[-1] self.deque.popleft() return parent.val def get_root(self): """ :rtype: TreeNode """ return self.root T = Tree().creat_tree("1 2 3 null null null 4 null null") obj = CBTInserter(T) print(obj.insert(7))
# 814. Binary Tree Pruning from tools import TreeNode, Tree #Created by bryantbyr on 20181119 #Time:O(N) #Space:O(1) #Tree + Recursion class Solution: def pruneTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root: return None root.left, root.right = self.pruneTree(root.left), self.pruneTree( root.right) return None if not root.right and not root.left and root.val == 0 else root S = Solution() T = Tree().creat_tree( "1 1 1 0 null null null 1 null null 0 0 null null 1 null null") Tree().front_recursion(S.pruneTree(T))
# 700. Search in a Binary Search Tree.py from tools import Tree, TreeNode #Created by bryantbyr on 20181117 #Time:O(N) #Space:O(1) #Tree + Binary Search class Solution: def searchBST(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ while root: if root.val < val: root = root.right elif root.val > val: root = root.left else: return root return None S = Solution() T = Tree().creat_tree("4 2 1 null null 3 null null 7 null null") Tree().front_recursion(S.searchBST(T, 3))
def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ vals = collections.deque(data.split()) def build_tree(): val = vals.popleft() if val != 'null': node = TreeNode(int(val)) node.left = build_tree() node.right = build_tree() return node else: return None return build_tree() # Your Codec object will be instantiated and called as such: codec = Codec() t = TreeNode(5) t.left = TreeNode(2) t.left.right = TreeNode(4) t.right = TreeNode(9) root = codec.deserialize(codec.serialize(t)) Tree().front_recursion(root)
#Learn from discuss on 20181114 #Time:O(N) #Space:O(1) #Tree + Recursion*/DFS* class Solution: def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ self.ans = float('-inf') def helper(node): if not node: return 0 # left, right = helper(node.left), helper(node.right) # self.ans = max(self.ans, node.val + left + right, node.val + left, node.val + right, node.val) # return max(node.val + left, node.val + right, node.val) left, right = max(helper(node.left), 0), max(helper(node.right), 0) self.ans = max(self.ans, node.val + left + right) return node.val + max(left, right) helper(root) return self.ans S = Solution() T = Tree().creat_tree("1 2 null null 3 null null") print(S.maxPathSum(T))
""" :type N: int :rtype: List[TreeNode] """ if N % 2 == 0: return [] def helper(n): if n == 1: return [TreeNode(0)] i, res = 1, [] while i < n - 1: left, right = helper(i), helper(n - 1 - i) for x in left: for y in right: root = TreeNode(0) root.left = x root.right = y res.append(root) i += 2 return res return helper(N) S = Solution() res = S.allPossibleFBT(5) for x in res: Tree().front_recursion(x) print("----")
head = head.next return length length = find_size(head) def helper(l, r): nonlocal head # 将head声明为外层变量 if l > r: return None mid = (l + r) // 2 left = helper(l, mid - 1) root = TreeNode(head.val) root.left = left head = head.next root.right = helper(mid + 1, r) return root return helper(0, length - 1) if __name__ == '__main__': S = Solution() L = ListNode(-10) L.next = ListNode(3) L.next.next = ListNode(0) L.next.next.next = ListNode(5) L.next.next.next.next = ListNode(9) Tree().front_recursion(S.sortedListToBST(L))
#Learn from discuss on 20181113 #Time:O(N) #Space:O(N) #Tree + Recursion* class Solution: def longestUnivaluePath(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0 def helper(node): if not node: return left_len, right_len = helper(node.left), helper(node.right) left = left_len + 1 if node.left and node.left.val == node.val else 0 right = right_len + 1 if node.right and node.right.val == node.val else 0 self.ans = max(self.ans, left + right) return max(left, right) helper(root) return self.ans S = Solution() T = Tree() t = T.creat_tree("1 4 4 null null 4 null null 5 null 5 null null") print(S.longestUnivaluePath(t))
else: if not temp.right: temp.right = TreeNode(val) break temp = temp.right return root #Learn from discuss on 20181118 #Time:O(N) #Space:O(1) #Tree + Recursion class Solution: def insertIntoBST(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ if not root: return TreeNode(val) if root.val > val: root.left = self.insertIntoBST(root.left, val) else: root.right = self.insertIntoBST(root.right, val) return root S = Solution() T = Tree().creat_tree("4 2 1 null null 3 null null 7 null null") Tree().front_recursion(S.insertIntoBST(T, 5))
#Time:O(N) #Space:O(N) #Tree + in-order traversal class Solution: def increasingBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ stack = [] isRoot, newRoot, res = True, None, None while root or stack: while root: stack.append(root) root = root.left root = stack.pop() if isRoot: res = newRoot = root isRoot = False else: root.left = None newRoot.right = root newRoot = root root = root.right return res S = Solution() T = Tree().creat_tree("5 3 2 1 null null null 4 null null 6 null 8 7 null null 9 null null") Tree().front_recursion(S.increasingBST(T))
:type root: TreeNode :type target: TreeNode :type K: int :rtype: List[int] """ conn = collections.defaultdict(set) def connect(root): if not root: return if root.left: conn[root.val].add(root.left.val) conn[root.left.val].add(root.val) if root.right: conn[root.val].add(root.right.val) conn[root.right.val].add(root.val) connect(root.left) connect(root.right) connect(root) res = [target.val] seen = set(res) for i in range(K): res = [y for x in res for y in conn[x] if y not in seen] seen |= set(res) return res s = Solution() T = Tree().creat_tree("1 null null") print(s.distanceK(T, TreeNode(1), 3))
else: pre = current.left while pre.right and pre.right != current: pre = pre.right if not pre.right: pre.right = current current = current.left else: if self.pre: if current.val < self.pre.val: if not self.first: self.first = self.pre if self.first: self.second = current self.pre = current pre.right = None current = current.right in_order_traversal(root) temp = self.second.val self.second.val = self.first.val self.first.val = temp S = Solution() T = Tree().creat_tree("3 1 null null 4 2 null null null") S.recoverTree(T) # Tree().front_recursion(T) Tree().inOrder_MorrisTraversal(T)