Below code calculates the diameter of a binary tree, but this is irrelevant here.
My problem is, that I’m confused why diameterOfBinaryTree1 returns 3 but diameterOfBinaryTree2 returns 2 for my input. It seems to me the only difference is one expression inlined or not. Any help appreciated.
(using jdk1.8.0_241)
public class Diameter_Binary_Tree {
int max = 0;
public int diameterOfBinaryTree1(TreeNode root) {
if (root == null) return 0;
int l = maxLength(root); // only difference compared to diameterOfBinaryTree2
max = Math.max(max, l); // only difference compared to diameterOfBinaryTree2
return max;
}
public int diameterOfBinaryTree2(TreeNode root) {
if (root == null) return 0;
max = Math.max(max, maxLength(root)); // only difference compared to diameterOfBinaryTree1
return max;
}
int maxLength(TreeNode node) {
int left = node.left == null ? 0 : maxLength(node.left) + 1;
int right = node.right == null ? 0 : maxLength(node.right) + 1;
max = Math.max(max, left + right);
return Math.max(left, right);
}
public static void main(String[] args) {
TreeNode n = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)), new TreeNode(3));
Diameter_Binary_Tree d1 = new Diameter_Binary_Tree();
System.out.println(d1.diameterOfBinaryTree1(n)); // prints 3
Diameter_Binary_Tree d2 = new Diameter_Binary_Tree();
System.out.println(d2.diameterOfBinaryTree2(n)); // prints 2
}
static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) { this.val = val; }
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}
>Solution :
On one hand it’s because you’re reusing the instance variable max in two of your methods (diameterOfBinaryTreeX and maxLength). On the other hand, the order of evaluation inside both diameterOfBinaryTreeX is different.
In diameterOfBinaryTree1:
int l = maxLength(root);
max = Math.max(max, l);
Here, because maxLength is evaluated first, the internal value of max is already changed when you reach Math.max which will ultimately result in Math.max(3, 2) = 3.
In diameterOfBinaryTree2
max = Math.max(max, maxLength(root));
Here, max is evaluated first, since Java evaluates left-to-right. When you reach maxLength the first parameter max is already fully evaluated and thus won’t be changed afterwards. The result will be Math.max(0, 2) = 2, which is what you found out 🙂