以下のコードでo/pを取得できません。私のcountinternalnodesは正しいですか? o/pを取得するためにmain関数で行う必要がある変更は何ですか?コードを実行するとエラーは発生しません。 countinternalnodes関数に変数を入力する方法。バイナリツリー操作メイン関数
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree {
Node root;
public void insert(int id){
Node newNode = new Node(id);
if(root==null){
root = newNode;
return;
}
Node current = root;
Node parent = null;
while(true){
parent = current;
if(id<current.data){
current = current.left;
if(current==null){
parent.left = newNode;
return;
}
}
else{
current = current.right;
if(current==null){
parent.right = newNode;
return;
}
}
}
}
public int getLeafCount()
{
return getLeafCount(root);
}
public int getLeafCount(Node node)
{
if (node == null)
return 0;
if (node.left == null && node.right == null)
return 1;
else
return getLeafCount(node.left) + getLeafCount(node.right);
}
public int numNodesIn(Node v) {
if (v == null) return 0;
return 1 + numNodesIn(v.left) + numNodesIn(v.right);
}
public int numEdgesIn(Node v) {
return v == null? 0 : numNodesIn(v) - 1;
}
public void display(Node root){
if(root!=null){
System.out.print(" " + root.data);
display(root.left);
display(root.right);
}
}
int countinternalnodes(Node e)
{
if(e == root)
{
return 0;
}
if(e.left == null && e.right == null)
{
return 1;
}
else
{
return countinternalnodes(e.left)+countinternalnodes(e.right);
}
}
public int maxDepth(Node root) {
if(root==null)
return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
int bigger = Math.max(leftDepth, rightDepth);
return bigger+1;
}
// Main Function
public static void main (String[] args)
{
BinaryTree b = new BinaryTree();
b.insert(3);b.insert(0);
b.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);
b.insert(20);b.insert(25);b.insert(15);b.insert(16);
System.out.println("Original Tree : ");
b.display(b.root);
System.out.println("count internal nodes : ");
b.countinternalnodes(b.root);// part is not working
b.maxDepth(b.root);
b.getLeafCount();
}
}