Given a binary tree to find its maximum depth.
The depth of the binary tree is the root node to the nodes on the longest path farthest leaf node.
Description: leaf node is a node has no child nodes.
Example:
Given binary tree [3,9,20, null, null, 15,7],
3
/ \
9 20
/ \
15 7
Return to its maximum depth of 3.
Ideas:
Dfs depth-first traversal use recursion to solve.
answer:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max=0;
int temp=0;
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int leftDeepth=maxDepth(root.left);
int rightDeepth=maxDepth(root.right);
return Math.max(leftDeepth,rightDeepth)+1;
}
}