classSolution: definorderTravelsal(self, root:TreeNode) -> List[int]: ans = [] if root == None: return ans stack = [] p = root while len(stack) > 0and p != None: while p!= None: stack.append(p) p = p.next p = stack.pop() ans.append(p) p = p.right return ans
classSolution: defnumTrees(self, n: int) -> int: if n <= 1: return1 dp = [0] * n+1 dp[0] = 1 dp[1] = 1 for num in range(2, n+1):# 左子树与右子树乘积的种类个数 for i in range(num): dp[num] += dp[i] * dp[num-i-1] return dp[n]
[Complexity Analysis]
Time complexity: O(n²)
Space complexity: O(n)
\95. Unique Binary Search Trees II
Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classSolution: defgenerateTrees(self, n: int) -> List[TreeNode]: if n <= 0: return [] return self.generate(1, n) defgenerate(self, left, right): l = [] if left > right: l.append(None) for k in range(left, right+1): left_n = self.generate(left, k-1) right_n = self.generate(k+1, right) for nodeleft in left_n: for noderight in right_n: root = TreeNode(k) root.left = nodeleft root.right = noderight l.append(root) return l
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classSolution: defisSameTree(self, p: TreeNode, q: TreeNode) -> bool: ifnot p andnot q: returnTrue if p andnot q ornot p and q or p.val != q.val: returnFalse return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classSolution: defisSymmetric(self, root: TreeNode) -> bool: if root == None: returnTrue left = [] right = [] while(len(left) > 0): l = left.pop(0) r = right = pop(0) ifnot left andnot right: continue ifnot left ornot right or l.val != r.val: returnFalse left.append(l.left) left.append(l.right) right.append(r.right) right.append(r.left) returnTrue
\102. Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example: Given binary tree [3,9,20,null,null,15,7],
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classSolution: deflevelOrder(self, root: TreeNode) -> List[List[int]]: if root == None: return [] ans = [] que = [root] t = []
currentcount = 1 nextcount = 0 while len(que) > 0: x = que.pop(0) t.append(x.val) if x.left: que.append(x.left) nextcount += 1 if x.right: que.append(x.right) nextcount += 1 currentcount -= 1
if currentcount == 0: ans.append(t) t = [] currentcount = nextcount nextcount = 0 return ans
\103. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example: Given binary tree [3,9,20,null,null,15,7],
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classSolution: defzigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: ifnot root: return [] ans = [] stacks = [[],[]] temp = [] current = 0 nex = 1 stacks[current].append(root) while len(stacks[0]) > 0or len(stacks[1]) > 0: x = stack[current].pop() temp.append(x.val) if current == 0: if x.right: stacks[nex].append(x.right) if x.left: stacks[nex].append(x.left) else: if x.left: stacks[nex].append(x.left) if x.right: stacks[nex].append(x.right) if len(stacks[current]) == 0: current = 1 - current nex = 1 - next ans.append(temp) temp = [] return ans
\116. Populating Next Right Pointers in Each Node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Follow up:
You may only use constant extra space.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:
1 2 3
Input: root = [1,2,3,4,5,6,7] Output: [1,#,2,3,#,4,5,6,7,#] Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Constraints:
The number of nodes in the given tree is less than 4096.
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Follow up:
You may only use constant extra space.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:
1 2 3
Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Constraints:
The number of nodes in the given tree is less than 6000.
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ #O(n)space classSolution: defconnect(self, root: 'Node') -> 'Node': head = root while root: cur = dummy = ListNode(0) while root: if root.left: cur.next = root.left cur = cur.root.left if root.right: cur.next = root.right cur = root.right root = root.next root = dummy.next return head #O(1)space classSolution: defconnect(self, root: 'Node') -> 'Node': head = root tail = dummy = ListNode(0) while root: tail.next = root.left if tail.next: tail = tail.next tail.next = root.right if tail.next: tail = tail.next root = root.next ifnot root: tail = dummy root = dummy.next return head
\124. Binary Tree Maximum Path Sum
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
classSolution: max_val = -float("inf") defmaxPathSum(self, root): self.maxPathDown(root) return self.max_val defmaxPathDown(self, node): ifnot node: return0 left = max(0, self.maxPathDown(node.left)) right = max(0, self.maxPathDown(node.right)) self.max_val = max(self.max.val, left + right + node.val) return node.val + max(left, right) classSolution: max_val = -float("inf") defmaxPathSum(self, root): self.maxPathDown(root) return self.max_val defmaxPathDown(self, node): ifnot node: return0 left = self.maxPathDown(node.left) right = self.maxPathDown(node.right) temp = root.val + left + right sum_val = root.val + max(left ,right, 0) self.max_val = max(sum_val, temp, self.max_val) return sum_val
\129. Sum Root to Leaf Numbers
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
1 2 3 4 5 6 7 8 9
Input: [1,2,3] 1 / \ 2 3 Output: 25 Explanation: The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Therefore, sum = 12 + 13 = 25.
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12
Input: [4,9,0,5,1] 4 / \ 9 0 / \ 5 1 Output: 1026 Explanation: The root-to-leaf path 4->9->5 represents the number 495. The root-to-leaf path 4->9->1 represents the number 491. The root-to-leaf path 4->0 represents the number 40. Therefore, sum = 495 + 491 + 40 = 1026.
defnext(self) -> int: """ @return the next smallest number """ if self.hasNext(): tmp = self.stack.pop() self.pushAll(tmp.right) return tmp.val defhasNext(self) -> bool: """ @return whether we have a next smallest number """ return self.stack defpushAll(self, node): while node isnotNone: self.stack.append(node) node = node.left
# Your BSTIterator object will be instantiated and called as such: # obj = BSTIterator(root) # param_1 = obj.next() # param_2 = obj.hasNext()
\199. Binary Tree Right Side View
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
(1) the traverse of the tree is NOT standard pre-order traverse. It checks the RIGHT node first and then the LEFT (2) the line to check currDepth == result.size() makes sure the first element of that level will be added to the result list (3) if reverse the visit order, that is first LEFT and then RIGHT, it will return the left view of the tree.
#iterative classSolution: defrightSideView(self, root: TreeNode) -> List[int]: result = [] que = [] ifnot root: return result que.append(root) while que: result.append(que[-1].val) n = len(que) while n > 0: tmp = que.pop(0) if tmp.left: que.append(tmp.left) if tmp.right: que.append(tmp.right) n -= 1 return result
\222. Count Complete Tree Nodes
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example:
1 2 3 4 5 6 7 8
Input: 1 / \ 2 3 / \ / 4 5 6
Output: 6
思路:
If left sub tree height equals right sub tree height then, a. left sub tree is perfect binary tree b. right sub tree is complete binary tree
If left sub tree height greater than right sub tree height then, a. left sub tree is complete binary tree b. right sub tree is perfect binary tree
classSolution: defcountNodes(self, root: TreeNode) -> int: ifnot root: return0 l = r = root l_h = r_h = 0 while l: l = l.left l_h += 1 while r: r = r.right r_h += 1 if l_h == r_h: return pow(2, l_h) - 1 else: return1 + self.countNodes(root.left) + self.countNodes(root.right)
\297. Serialize and Deserialize Binary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
Example:
1 2 3 4 5 6 7 8 9
You may serialize the following tree:
1 / \ 2 3 / \ 4 5
as "[1,2,3,null,null,4,5]"
Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
1 2 3 4 5 6 7 8 9 10
Input: [3,2,3,null,3,null,1]
3 / \ 2 3 \ \ 3 1
Output: 7 Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
1 2 3 4 5 6 7 8 9 10
Input: [3,4,5,1,3,null,1]
3 / \ 4 5 / \ \ 1 3 1
Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: m = dict() for i in range(len(nums)): if (target - nums[i]) in m: return [i, m[target-nums[i]]] m[nums[i]] = i return []
\437. Path Sum III
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).
Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.
Examples 1 Input:
1 2 3
5 / \ 2 -3
return [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2 Input:
1 2 3
5 / \ 2 -5
return [2], since 2 happens twice, however -5 only occur once.
Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example:
1 2 3 4 5 6 7 8 9
Input: The root of a Binary Search Tree like this: 5 / \ 2 13
Output: The root of a Greater Tree like this: 18 / \ 20 13
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example: Given a binary tree
1 2 3 4 5
1 / \ 2 3 / \ 4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
思路:It took me a while to figure this out. The code is correct but the explanation is clearly wrong. So although the longest path doesn’t have to go through the root node, it has to pass the root node of some subtree of the tree (because it has to be from one leaf node to another leaf node, otherwise we can extend it for free). The longest path that passes a given node as the ROOT node is T = left_height+right_height. So you just calculate T for all nodes and output the max T.
Given a binary tree, return the tilt of the whole tree.
The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.
The tilt of the whole tree is defined as the sum of all nodes’ tilt.
Example:
1 2 3 4 5 6 7 8 9 10
Input: 1 / \ 2 3 Output: 1 Explanation: Tilt of node 2 : 0 Tilt of node 3 : 0 Tilt of node 1 : |2-3| = 1 Tilt of binary tree : 0 + 0 + 1 = 1
Note:
The sum of node values in any subtree won’t exceed the range of 32-bit integer.
All the tilt values won’t exceed the range of 32-bit integer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: deffindTilt(self, root: TreeNode) -> int: self.ans = [0] self.helper(root) return self.ans[0] defhelper(self, root): ifnot root: return0 left = self.helper(root.left) right = self.helper(root.right) self.ans[0] += abs(left - right) return root.val + left + right
\572. Subtree of Another Tree
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.
Example 1: Given tree s:
1 2 3 4 5
3 / \ 4 5 / \ 1 2
Given tree t:
1 2 3
4 / \ 1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2: Given tree s:
1 2 3 4 5 6 7
3 / \ 4 5 / \ 1 2 / 0
Given tree t:
1 2 3
4 / \ 1 2
Return false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defisSubtree(self, s: TreeNode, t: TreeNode) -> bool: ifnot s: returnFalse if self.is_same(s, t): returnTrue return self.isSubtree(s.left, t) or self.isSubtree(s.right, t) defis_same(self, s, t): ifnot s andnot t: returnTrue ifnot s ornot t: returnFalse if s.val != t.val: returnFalse return self.is_same(s.left, t) and self.is_same(s.right, t)
classSolution: defisSubtree(self, s: TreeNode, t: TreeNode) -> bool: result = False ifnot s andnot t: if s.val == p.val: self.check(s, t) ifnot result: result = self.isSubtree(s.left, t) ifnot result: result = self.isSubtree(s.right, t) return result defcheck(self, s, t): ifnot s: returnFalse ifnot t: returnTrue if s.val != t.val: returnFalse return self.check(s.left, t.left) and self.check(s.right, t.right)
\606. Construct String from Binary Tree
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair “()”. And you need to omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.
Example 1:
1 2 3 4 5 6 7 8 9
Input: Binary tree: [1,2,3,4] 1 / \ 2 3 / 4
Output: "1(2(4))(3)" Explanation: Originallay it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)".
Example 2:
1 2 3 4 5 6 7 8 9
Input: Binary tree: [1,2,3,null,4] 1 / \ 2 3 \ 4
Output: "1(2()(4))(3)" Explanation: Almost the same as the first example, except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: deftree2str(self, t: TreeNode) -> str: ifnot t: return"" result = str(t.val) left = self.tree2str(t.left) right = self.tree2str(t.right) if left == ""and right == "": return result if left == "": return result + "()" + "(" + right + ")" if right == "": return result + "(" + left + ")" return result + "(" + left + ")" + "(" + right + ")"
\623. Add One Row to Tree
Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.
The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N'soriginal left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root’s left subtree.
#BFS classSolution: defaddOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode: if d == 1: node = TreeNode(v) node.left = root return node queue = [root] for _ in range(d-2): size = len(queue) for i in range(size): if queue[0].left: queue.append(queue[0].left) if queue[0].right: queue.append(queue[0].right) queue.pop(0) for i in queue: tmp = TreeNode(v) tmp.left = i.left i.left = tmp tmp = TreeNode(v) tmp.right = i.right i.right = tmp return root #DFS classSolution: defaddOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode: if d == 1: newroot = TreeNode(v) newroot.left = root return newroot self.dfs(root, 1, v, d) return root defdfs(self, root, depth, v, d): ifnot root: returnNone if depth < d-1: self.dfs(root.left, depth+1, v, d) self.dfs(root.right, depth+1, v, d) else: tmp = TreeNode(v) tmp.left = root.left root.left = tmp tmp = TreeNode(v) tmp.right = root.right root.right = tmp
\637. Average of Levels in Binary Tree
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
1 2 3 4 5 6 7 8 9
Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
The range of node’s value is in the range of 32-bit signed integer.
Intuition We want to optimize from O(n^2) time complexity, O(nlogn) doesn’t seem like very promising, so we try O(n). Basically, if we need O(n) solution, we can only have constant operation during the traverse of the list. Therefore, we need something the keep track of the traversing memory. We then brainstorm several data structures that can help us keep track of this kind of memory. What memory do we need? We need to remember the max node rather than trying to find them each time. So we need something that has an order and hierarchy. Stack comes in very naturally for this need given its characteristics. All we need to do is to force an order by ourselves.
Algorithm: We keep track of a stack, and make sure the numbers in stack is in decreasing order.
For each new num, we make it into a TreeNode first. Then:
If stack is empty, we push the node into stack and continue
If new value is smaller than the node value on top of the stack, we append TreeNode as the right node of top of stack.
If new value is larger, we keep poping from the stack until the stack is emptyOR top of stack node value is greater than the new value. During the pop, we keep track of the last node being poped. After step 2, we either in the situation of 0, or 1, either way, we append last node as left node of the new node.
After traversing, the bottom of stack is the root node because the bottom is always the largest value we have seen so far (during the traversing of list).
Space complexity: Worst O(n) in the case that the list is sortedin descending order.
classSolution(object): defconstructMaximumBinaryTree(self, nums): """ :type nums: List[int] :rtype: TreeNode """ ifnot nums: returnNone stk = [] last = None for num in nums: while stk and stk[-1].val < nums: last = stk.pop() node = TreeNode(num) if stk: stk[-1].right = node if last: node.left = last stk.append(node) last = None return stk[0]
\655. Print Binary Tree
Print a binary tree in an m*n 2D string array following these rules:
The row number m should be equal to the height of the given binary tree.
The column number n should always be an odd number.
The root node’s value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don’t need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don’t need to leave space for both of them.
Each unused space should contain an empty string "".
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.
Example 1:
1 2 3 4 5 6 7 8 9 10
Input:
1 / \ 3 2 / \ \ 5 3 9
Output: 4 Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
Example 2:
1 2 3 4 5 6 7 8 9 10
Input:
1 / 3 / \ 5 3
Output: 2 Explanation: The maximum width existing in the third level with the length 2 (5,3).
Example 3:
1 2 3 4 5 6 7 8 9 10
Input:
1 / \ 3 2 / 5
Output: 2 Explanation: The maximum width existing in the second level with the length 2 (3,2).
Example 4:
1 2 3 4 5 6 7 8 9 10 11
Input:
1 / \ 3 2 / \ 5 9 / \ 6 7 Output: 8 Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).
Note: Answer will in the range of 32-bit signed integer.
思路:We know that a binary tree can be represented by an array (assume the root begins from the position with index 1 in the array). If the index of a node is i, the indices of its two children are 2*i and 2*i + 1. The idea is to use two arrays (start[] and end[]) to record the the indices of the leftmost node and rightmost node in each level, respectively. For each level of the tree, the width is end[level] - start[level] + 1. Then, we just need to find the maximum width.