defrecoverTree(self,root: TreeNode) ->None: x = y = pre =None stack = [] node = rootwhile stack or node:while node: stack.append(node) node = node.left node = stack.pop()# 先遇到 x or y, pre代表的點不一樣if pre and pre.val > node.val: y = nodeif x ==None: x = preelse:break pre = node node = node.right x.val, y.val = y.val, x.val
Recursive
defrecoverTree(self,root: TreeNode) ->None:deffind_swap(node):nonlocal x, y, preifnot node:returnfind_swap(node.left)if pre and pre.val > node.val: y = node# first swap pointif x ==None: x = pre# second swap pointelse:return pre = nodefind_swap(node.right) x = y = pre =Nonefind_swap(root) x.val, y.val = y.val, x.val
Morris
defrecoverTree(self,root: TreeNode) ->None:deffindPredecessor(node): pre = node.leftwhile pre.right and pre.right != node: pre = pre.rightreturn pre cur = root x = y = pre =Nonewhile cur:if cur.left: predecessor =findPredecessor(cur)ifnot predecessor.right: predecessor.right = cur cur = cur.leftelse:if pre and pre.val > cur.val: y = curifnot x: x = pre# will casue cycle if break the loop# else:# break predecessor.right =None pre = cur cur = cur.rightelse:if pre and pre.val > cur.val: y = curifnot x: x = pre# will casue cycle if break the loop#else:# break pre = cur cur = cur.right x.val, y.val = y.val, x.val
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Use a stack to store next smallest number
apply addLeft method, add left nodes to stack
publicclassBSTIterator {privateStack<TreeNode> s =newStack<>();publicBSTIterator(TreeNode root) {addLeft(root); } /** @return whether we have a next smallest number */publicbooleanhasNext() {return!s.isEmpty(); } /** @return the next smallest number */publicintnext() {TreeNode tmp =s.pop();addLeft(tmp.right);returntmp.val; }privatevoidaddLeft(TreeNode node){while(node !=null){s.push(node); node =node.left; } }}
285 Inorder successor in BST
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null.
publicTreeNodeinorderSuccessor(TreeNode root,TreeNode p) {if (root ==null){returnnull; }if (root.val<=p.val){returninorderSuccessor(root.right, p); }TreeNode left =inorderSuccessor(root.left, p);return left ==null? root : left;}
510 Inorder Successor in BST II
Given a node in a binary search tree, find the in-order successor of that node in the BST. If that node has no in-order successor, return null. The Node has parent attribute
definorderSuccessor(self,node:'Node') ->'Node':# if successor in right childif node.right: node = node.rightwhile node.left: node = node.leftreturn node# if successor in upper level (this including no successor case)while node.parent and node.parent.right == node: node = node.parentreturn node.parent
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
"""A tree node, with count value represent smaller countsTraverse from end, build the tree and count number of smaller nodes"""classNode:def__init__(self,val): self.val = val self.left =None self.right =None self.count =1# 小於等於自己的node個數classSolution:defcountSmaller(self,nums: List[int]) -> List[int]:ifnot nums:return [] root =Node(nums[-1]) res = [0]# starting from last 2nd idx in reverse orderfor n in nums[-2::-1]: count = self.insert(root, n) res.append(count)return res[::-1]definsert(self,node,val): count =0whileTrue:if val <= node.val: node.count +=1ifnot node.left: node.left =Node(val)breakelse: node = node.leftelse: count += node.countifnot node.right: node.right =Node(val)breakelse: node = node.rightreturn count