﻿ algorithm – 排序列表以完成BST数组表示 - 代码日志

#### algorithm – 排序列表以完成BST数组表示

``````     4
2     6
1   3  5
``````

``````findRoot(int[] arr , int maxLeaves , int maxLevelL)
//maxLeaves is the number of leaves on the maximum-level
int l = min(maxLevelL / 2 , maxLeaves)
return (arr.length - maxLeaves) / 2 + l

node buildTree(int[] arr , int maxLeaves , int maxLevelL)
if maxLevelL == 0
return null

node result
int rootidx = findRoot(arr , maxLeaves)

result.val = arr[rootidx]

result.left = buildTree(arr.subarray(0 , rootidx) , Math.min(maxLeaves , rootidx - 1) , maxLevelL / 2)
result.right = buildTree(arr.subarray(rootidx + 1 , arr.length) , Math.max(0 , maxLeaves - rootidx - 1) , maxLevelL / 2)

return node
``````

``````if m - x == m / 2 then both are complete and the height of RS is height(LS) - 1
if m - x < m / 2 RS is perfect, LS only complete but not perfect
if m - x > m / 2 LS is perfect, RS only complete but not perfect
if m - x == 0 both LS and RS are perfect and of equal height
``````

``````E.g.:
Input:   1  2  3  4  5
Nodes on maxLevel: 2
maxLevelL: 4

l = 2
r = 0

root_idx = (arr.length - (l + r)) / 2 + l =
= (5 - 2) / 2 + 2 =
= 3

Apply this algorithm recursively to define subtrees:
...

result:
4
/   \
2     5
/   \
1     3
``````

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.

from wikipedia

>树的根有索引0
>索引为n的节点的左子节点具有索引(n 1)* 2 – 1
>索引为n的节点的右子节点具有索引(n 1)* 2

``````node buildTree(int[] arr , int maxLeaves , int maxLevelL ,
int[] result , int nodeidx)
if maxLevelL == 0
return

int rootidx = findRoot(arr , maxLeaves)

//insert value into correct position of result-array
result[nodeidx] = arr[rootidx]

//build left subtree
buildTree(arr.subarray(0 , rootidx) , Math.min(maxLeaves , rootidx - 1) , maxLevelL / 2 ,
result , (nodeidx + 1) * 2 - 1)

//build right subtree
buildTree(arr.subarray(rootidx + 1 , arr.length) , Math.max(0 , maxLeaves - rootidx - 1) , maxLevelL / 2 ,
result , (nodeidx + 1) * 2)
``````