Problem #104: Maximum Depth of Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
int lDepth = maxDepth(root.left);
int rDepth = maxDepth(root.right);
return Math.max(lDepth, rDepth)+1;
}
}Problem #543: Diameter of a Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int height(TreeNode root) {
if (root == null)
return -1;
return Math.max(height(root.left), height(root.right)) + 1;
}
public int diameterOfBinaryTree(TreeNode root) {
if (root == null)
return 0;
int lHeight = height(root.left);
int rHeight = height(root.right);
int lDiameter = diameterOfBinaryTree(root.left);
int rDiameter = diameterOfBinaryTree(root.right);
return Math.max(lHeight+rHeight+2 , Math.max(lDiameter, rDiameter));
}
}~~~
I plan to extend this category of posts with more related ones to come soon!
Until then,
Happy Problem Solving!!
No comments:
Post a Comment