Advertisement

binary tree depth

阅读量:

确定一棵二叉树的最大深度值。
二叉树的深度定义为从根节点至最远叶节点路径中所包含的节点总数。

通过递归方式将问题进行分解

取1与左子树最大深度和右子树最大深度中较大者的总和

  1. 若树为空,则其深度为0
  2. 当仅存在根节点而无左右子树时,其深度为1
  3. 1 加上左子树与右子树深度中的最大值
复制代码
    /** * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);

全部评论 (0)

还没有任何评论哟~