Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search Coderanch
Advance search
Google search
Register / Login
Zeny Auro
Greenhorn
+ Follow
1
Posts
1
Threads
0
Cows
since Jul 07, 2019
Merit badge:
grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
Ranch Hand Scavenger Hunt
Number Posts (1/100)
Number Threads Started (1/100)
Number Cows Received (0/5)
Number Likes Received (0/10)
Number Likes Granted (0/20)
Set bumper stickers in profile (0/3)
Report a post to the moderators (0/1)
Edit a wiki page (0/1)
Create a post with an image (0/2)
Greenhorn Scavenger Hunt
First Post
Number Posts (1/10)
Number Threads Started (1/10)
Number Likes Received (0/3)
Number Likes Granted (0/3)
Set bumper stickers in profile (0/1)
Set signature in profile
Search for a post/thread (0/3)
Set a watch on a thread
Save thread as a bookmark
Create a post with an image (0/1)
Recent posts by Zeny Auro
I am struggling with understand the following solution the diameter of a binary tree.
I am struggling to understand(visualise) what height() function does.
class BinaryTree { /* Tree node structure used in the program */ static class Node { int data; Node left, right; } static class A { int ans = Integer.MIN_VALUE; } /* Function to find height of a tree */ static int height(Node root, A a) { if (root == null) return 0; int left_height = height(root.left, a); int right_height = height(root.right, a); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node a.ans = Math.max(a.ans, 1 + left_height + right_height); return 1 + Math.max(left_height, right_height); } /* Computes the diameter of binary tree with given root. */ static int diameter(Node root) { if (root == null) return 0; // This will store the final answer A a = new A(); int height_of_tree = height(root, a); return a.ans; } static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node); } // Driver code public static void main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); System.out.println("Diameter is " + diameter(root)); } }
show more
4 years ago
Java in General