我想创建一个完整的二叉树,该树以递归方式将String值保存在其叶子中。
示例1: 假设您要在树中保存两个字符串。因此,您将需要一个根和两片叶子。
* <- root node
/ \
v0 v1 <- leaves
示例2: 假设您要在树中保存三个字符串。因此,您将需要一个根,两个内部节点和四个叶子,因此树仍然完整。
* <- root node
/ \
+ + <- inner node
/ \
/ \
/ \ / \
v0 v1 v2 v3 <- leaves
计算二叉树的规格非常简单。
高度:⌈log2预期为NumOfStrings⌉
double height = Math.log(expectedNumOfStrings) / Math.log(2);
int roundedHeight = (int) Math.ceil(height);
叶片数:2 高度
int numOfLeaves = (int) Math.pow(2, roundedHeight);
内部节点数: 2 h − 1
int numOfInnerNodes = (int) (Math.pow(2, roundedHeight)-1)
让我们为该二叉树实现几个类。我们需要一个BinaryTree
类。
/**
* Create a complete binary tree recursively depending on the expected leaves.
*/
public class BinaryTree {
private InnerNode root;
private LeafNode current;
public BinaryTree(int expectedNumOfStrings) {
//sets root node
this.root = new InnerNode();
//set inner nodes
root.createInnerNodes(expectedNumOfStrings);
//set leaves
root.createLeaves(expectedNumOfStrings);
//The way things are now the tree isn't created in one go.
//I'll have to traverse it again for the leaves.
}
}
树的所有元素共享一个到父级的链接(对于根,它是null
)。让我们创建一个类TreeNode
:
public class TreeNode {
private TreeNode parent;
}
现在,我们创建InnerNode
和LeafNode
,它们只是扩展TreeNode。
public class InnerNode extends TreeNode {
private BinaryTree left;
private BinaryTree right;
//used to set the root node
public InnerNode() {
super.parent = null;
this.left=null;
this.right=null;
}
public InnerNode(InnerNode parent) {
super.parent= parent;
}
public TreeNode createInnerNodes(int expectedValues) {
//recursive magic happens here. But how?
}
}
和
public class LeafNode extends TreeNode {
private String data;
public LeafNode(InnerNode parent) {
super.parent= parent;
}
public LeafNode createLeaves(int numOfLeaves) {
//recursive magic happens here again. But how?
}
}
InnerNodes
和Leaves
?InnerNode left
和InnerNode right
是私有的,因此我只能从InnerNode
中访问它们。但是我该如何处理树叶呢?我可以通过方法将根节点传递给InnerNode
/ Leaves
吗?