Here is one recursive solution of the problem:
TreeNode toTree(ArrayListarray){ if (array == null || array.size() == 0) { return null; } TreeNode result = new TreeNode(array.get(0)); for (int i = 1; i < array.size(); i++) { addTo(result, array.get(i)); } return result; } void addTo(TreeNode node, int i) { if (i < node.d) { if (node.getLeft() == null) { node.setLeft(new TreeNode(i)); } else { addTo(node.getLeft(), i); } } else { if (node.getRight() == null) { node.setRight(new TreeNode(i)); } else { addTo(node.getRight(), i); } } }
No comments:
Post a Comment