java如何减少全局变量的使用_java - 如何避免在此处使用全局变量? - SO中文参考 - www.soinside.com...

您可以使用此代码解决问题:// Recursive optimized Java program to find the diameter of a

// Binary Tree

/* Class containing left and right child of current

node and key value*/

class Node

{

int data;

Node left, right;

public Node(int item)

{

data = item;

left = right = null;

}

}

/* Class to print the Diameter */

class BinaryTree

{

Node root;

/* Method to calculate the diameter and return it to main */

int diameter(Node root)

{

/* base case if tree is empty */

if (root == null)

return 0;

/* get the height of left and right sub trees */

int lheight = height(root.left);

int rheight = height(root.right);

/* get the diameter of left and right subtrees */

int ldiameter = diameter(root.left);

int rdiameter = diameter(root.right);

/* Return max of following three

1) Diameter of left subtree

2) Diameter of right subtree

3) Height of left subtree + height of right subtree + 1 */

return Math.max(lheight + rheight + 1,

Math.max(ldiameter, rdiameter));

}

/* A wrapper over diameter(Node root) */

int diameter()

{

return diameter(root);

}

/*The function Compute the "height" of a tree. Height is the

number f nodes along the longest path from the root node

down to the farthest leaf node.*/

static int height(Node node)

{

/* base case tree is empty */

if (node == null)

return 0;

/* If tree is not empty then height = 1 + max of left

height and right heights */

return (1 + Math.max(height(node.left), height(node.right)));

}

public static void main(String args[])

{

/* creating a binary tree and entering the nodes */

BinaryTree tree = new BinaryTree();

tree.root = new Node(1);

tree.root.left = new Node(2);

tree.root.right = new Node(3);

tree.root.left.left = new Node(4);

tree.root.left.right = new Node(5);

System.out.println("The diameter of given binary tree is : "

+ tree.diameter());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值