【发布时间】:2014-01-14 20:01:54
【问题描述】:
我有这段代码,用于从预排序遍历元素的扁平列表中重建二叉搜索树。
我看到此代码有效,但无法理解如何。代码如下:
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);
}
【问题讨论】:
标签: java binary-tree binary-search-tree preorder