我有这段代码用于从预排序遍历元素的扁平列表中重建二叉搜索树。
我看到这段代码工作,但无法理解如何。这是代码:
public static Node reconstructfromflattenBST(List<Integer> list){
if (list.isEmpty()){
return null;
}
int data = list.remove(0);
Node root = new Node(data);
root.left=reconstructfromflattenBST(list);
root.right=reconstructfromflattenBST(list);
return root;
}
根据我对这种方法的理解,不会创建正确的树。因为当控制到达时root.right
,list
是空的。但这种方法显然有效。
我给出了 [5 3 1 4 8 6 9] 的预购输入。构建树后,我对构建的树进行了前序遍历,它给出了与输入列表相同的元素顺序。
编辑:这是我的展平子程序:
public static List<Integer> flattenBinaryTree(Node root, List<Integer> list){
if (list==null){
list=new ArrayList<Integer>();
}
if (root==null){
return list;
}
list.add(root.data);
List<Integer> list1 = flattenBinaryTree(root.left,list);
return flattenBinaryTree(root.right, list1);
}