Given the head node of a binary tree, it is known that the values of all the nodes are not the same, find the two fork tree with the most nodes in the search, and return the head node of this subtree.
For example
Max search subtree as right
First of all to explain what is the largest search subtree, is the binary search tree, the value of any node must be greater than the maximum number of left subtree, less than the minimum value of the right subtree, and the subtree is a two-fork search tree.
So it is easy to think of using recursive return to solve problems.
1. The entire process uses post-processing traversal
2. When the current node is recorded as Cur, the cur's left subtree is traversed to collect 4 information, namely the head node (LBST), the number of nodes (lsize), the minimum (lMin), and the maximum (LMax) of the largest binary tree on the left subtree. The right subtree of the cur is then traversed to collect 4 messages, the head node (RBST), the number of nodes (rsize), the minimum (rMin), and the maximum (RMax) of the two fork trees on the right subtree, respectively.
3. According to the information collected in step 2, determine whether to satisfy the definition of the search subtree, if satisfied, return to the CUR node, if not satisfied, returns the number of nodes in Lbst and rBST
1 Publicnode Biggestsubbst (node head) {2 int[] record =New int[3];3 returnPosorder (head, record);4 }5 6 PublicNode Posorder (node head,int[] record) {7 if(Head = =NULL) {8Record[0] = 0;9RECORD[1] =Integer.max_value;TenRECORD[2] =Integer.min_value; One return NULL; A } - intValue =Head.value; -Node left =Head.left; theNode right =Head.right; -Node Lbst =Posorder (left, record); - intLsize = record[0]; - intLMin = record[1]; + intLMax = record[2]; -Node rBST =Posorder (right, record); + intRsize = record[0]; A intRMin = record[1]; at intRMax = record[2]; - -RECORD[1] =math.min (lMin, value); -RECORD[2] =Math.max (RMax, value); - - if(left = = Lbst && right = = rBST && LMax < value && Value <rMin) { inRecord[0] = lsize + rsize + 1; - returnhead; to } + -Record[0] =Math.max (lsize, rsize); the returnLsize > Rsize?Lbst:rbst; *}
Programmer Code Interview Guide left Chengyun
One-day algorithm puzzle (6)---Find the largest two fork tree in a two-fork tree