LeetCode-Maximum Depth of Binary Tree
- Problem:
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
- analysis:
利用递归求左节点和右节点较大值,然后再加一。
- anwser:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
int leftMaxDepth,rightMaxDepth;
if(root == null) return 0;
leftMaxDepth = maxDepth(root.left);
rightMaxDepth = maxDepth(root.right);
return max(leftMaxDepth,rightMaxDepth) + 1;
}
public int max(int a,int b){
if(a>b) return a;
else return b;
}
}
还没有评论,来说两句吧...