/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
public int val;
val = x;
}
}
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public int diameterOfBinaryTree
(TreeNode root
) {
Map
<TreeNode, Integer
> map
= new HashMap
<>(); Stack<TreeNode> stack = new Stack<>();
int diameter = 0;
if (root != null)
stack.push(root);
while (!stack.isEmpty()) {
// Fill up stack to perform post-order traversal
if (node.left != null && !map.containsKey(node.left)) {
stack.push(node.left);
} else if (node.right != null && !map.containsKey(node.right)) {
stack.push(node.right);
} else {
// Process the root, once left and right sub-tree have been processed
stack.pop();
int leftDepth = map.getOrDefault(node.left, 0);
int rightDepth = map.getOrDefault(node.right, 0);
// Put the max depth at a node in the map
map.
put(node,
1 + Math.
max(leftDepth, rightDepth
));
// Update the max diameter found so far
diameter
= Math.
max(diameter, leftDepth
+ rightDepth
); }
}
return diameter;
}
{
Ideone diameterOfABinaryTree = new Ideone();
// your code goes here
//
// 1
// / \
// 2 3
// / \
// 4 5
System.
out.
println(diameterOfABinaryTree.
diameterOfBinaryTree(root
)); }
}
LyogcGFja2FnZSB3aGF0ZXZlcjsgLy8gZG9uJ3QgcGxhY2UgcGFja2FnZSBuYW1lISAqLwoKaW1wb3J0IGphdmEudXRpbC4qOwppbXBvcnQgamF2YS5sYW5nLio7CmltcG9ydCBqYXZhLmlvLio7CgpjbGFzcyBUcmVlTm9kZSB7CgogIHB1YmxpYyBpbnQgdmFsOwogIHB1YmxpYyBUcmVlTm9kZSBsZWZ0OwogIHB1YmxpYyBUcmVlTm9kZSByaWdodDsKCiAgcHVibGljIFRyZWVOb2RlKGludCB4KSB7CiAgICB2YWwgPSB4OwogIH0KfQovKiBOYW1lIG9mIHRoZSBjbGFzcyBoYXMgdG8gYmUgIk1haW4iIG9ubHkgaWYgdGhlIGNsYXNzIGlzIHB1YmxpYy4gKi8KY2xhc3MgSWRlb25lCnsKCXB1YmxpYyBpbnQgZGlhbWV0ZXJPZkJpbmFyeVRyZWUo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