Return a list of the values of all nodes that have a distance K from the target node.
"""分target以上level跟以下level討論1. 以下level找到distance為k的node2. 往上recursive找到距離為k的upper level node, 繼續往上,網left and right node找"""classSolution:defdistanceK(self,root: TreeNode,target: TreeNode,K:int) -> List[int]: self.ans = [] self.dfs(root, target, K)return self.ans# return the distance to node targetdefdfs(self,node,target,K):ifnot node:return-1elif node == target: self.addNodes(node, K)return1else: L, R = self.dfs(node.left, target, K), self.dfs(node.right, target, K)if L !=-1and L <= K:if L == K: self.ans.append(node.val)# target 在left child, 往 right child 移動 self.addNodes(node.right, K-L-1)return L+1elif R !=-1and R<=K:if R == K: self.ans.append(node.val) self.addNodes(node.left, K-R-1)return R+1else:return-1defaddNodes(self,node,K):ifnot node:returnif K==0: self.ans.append(node.val) self.addNodes(node.left, K-1) self.addNodes(node.right, K-1)
1145. Binary Tree Coloring Game
Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n.
The first player colors the node with value x red, and the second player colors the node with value y blue.
return if second player can win the game
The best chance to win is choosing node next to x, the players 1 can't cross this node, players can take the child nodes all.
3 possibilities: left child, right child, and parent node
Return if candidate subtree is greater than total number of nodes
defbtreeGameWinningMove(self,root: TreeNode,n:int,x:int) ->bool: l, r =0,0defcount(node):nonlocal l, rifnot node:return0 left =count(node.left) right =count(node.right)# meet x node, update the left child and right child candidate if node.val == x: l, r = left, rightreturn1+ left + right total =count(root)returnmax(max(l, r), n - l - r -1)> total //2