0
binary tree
を作成するためにこのコードを作成しましたが、このコードはunbalanced binary tree
を作成しているようです。ノードは、right
サブツリーroot
でのみ取得しています。左のサブツリーの子ノードにアクセスしようとするとNull pointer exception
が出ます。ノードがleft to right
から挿入されているbalanced binary tree
を作成したいと思います。私はここで何をしているのですか?Javaを使用して平衡二分木を作成する際にエラーが発生しました
public class binTree {
public static class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val){
this.val = val;
this.left = null;
this.right = null;
}
}
public TreeNode root;
public binTree(){
this.root = null;
}
public void insert(int data){
root = insert(root,data);
}
public TreeNode insert(TreeNode node,int data){
if(node == null){
node = new TreeNode(data);
//root = node;
}
else{
if(node.left == null){
node.left = insert(node.left,data);
}
else{
node.right = insert(node.right,data);
}
}
return node;
}
public static void main(String args[]){
binTree obj = new binTree();
obj.insert(5);
obj.insert(11);
obj.insert(13);
obj.insert(1);
obj.insert(7);
obj.insert(21);
obj.insert(35);
System.out.println(obj.root.right.left.val);
System.out.println(obj.root.left.right.val); // this throws null pointer exception
}
}
あなたは '高さを()'説明することができますか?私は各サブツリーの要素の数が 'height()'でどのように計算されているのかを知っていますか? – user2916886
@ user2916886 heightは、完全なサブツリーを深く計算します。 –