def helper(self, low, high): result = [] # Creating a list to store all the nodes if low > high: result.append(None) for i in range(low, high + 1): left = self.helper(low, i - 1) right = self.helper(i + 1, high) for j in left: for k in right: curr = Node(i) curr.left = j curr.right = k result.append(curr) return result
queue.append(curr.right) hd_node[curr.right] = hd_node[curr] + 1 hd = hd_node[curr.right] if v_node.get(hd) is None: v_node[hd] = [] v_node[hd].append(curr.right.data) sorted_m = OrderedDict(sorted( v_node.items())) # sort the dict in order using distance return list(sorted_m.values()) s = Solution() root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.right.left.right = Node(8) root.right.right.left = Node(10) root.right.right.right = Node(9) root.right.right.left.right = Node(11) root.right.right.left.right.right = Node(12) print(s.vertical_traversal(root)) root.tree_traversal()
stack.append((root.right, False)) stack.append((root.left, False)) return result # Using recursion def postorderTraversal(self, root): res = [] if root is None: return res self.helper(root, res) return res def helper(self, node, res): if node is None: return self.helper(node.left, res) self.helper(node.right, res) res.append(node.val) """ Testing Code """ from Python.Level6.TreeDataStructure import Node s = Solution() root = Node(1) root.right = Node(2) root.right.left = Node(3) print(s.inorder_traversal(root))
return target == 0 else: res = 0 target -= root.data if target == 0 and root.left is None and root.right is None: return 1 if root.left: res = res or self.path_sum(root.left, target) if root.right: res = res or self.path_sum(root.right, target) return res """Testing program""" s = Solution() root = Node(5) root.left = Node(4) root.right = Node(8) root.left.left = Node(11) root.right.left = Node(13) root.right.right = Node(4) root.left.left.left = Node(7) root.left.left.right = Node(2) root.right.right.right = Node(1) print(s.path_sum(root, 22))