説明
その最大の深さを見つけるためのバイナリツリーを考えます。
最も遠い距離にルートノードにバイナリツリーのリーフノードの深さ。
あなたは本当のインタビューで、この問題が発生したことがありますか?
サンプル
サンプル1:
入力:木= {}
出力:0
サンプル説明:0は空のツリーの深さです。
サンプル2:
入力:木= {1,2,3、#、 #、4,5}を
出力:3
サンプルは説明:ツリーは3の深さ以下の
1
/ \
23
/ \
45
には、{1としてシリアル化されます、2,3、#、#、4,5}
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer
*/
public int maxDepth(TreeNode root) {
// write your code here
if (root == null) {
return 0;
}
int resLeft = maxDepth(root.left) + 1;
int resRight = maxDepth(root.right) + 1;
return Math.max(resLeft, resRight);
}
}