leetcode 104. Maximum Depth of Binary Tree

题目描述:

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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

思路:

递归:

需要定义一个全局变量来记录遍历当前节点处二叉树的最大深度。每次深度搜索时,当前深度都要进行+1操作,并且每到达一个新的节点处,都需要将当前深度和全局的最大深度进行比较,若当前深度大于全局最大深度,则更新全局最大深度。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int depth=0;
    public int maxDepth(TreeNode root) {
        helper(root,1);
        return depth;
    }
    private void helper(TreeNode node,int currDepth){
        if(node==null){
            return;
        }
        if(currDepth>depth){
            depth=currDepth;
        }
        helper(node.left,currDepth+1);
        helper(node.right,currDepth+1);
    }
}

分治:

关于二叉树的问题,都推荐用分治的思想去解决,清楚明了。本题用分治的方法就是,定义一种递归的算法,从根节点开始,我们就递归的去寻找当前根节点对应的左子树和右子树的深度,那么整棵树的最大深度就是左子树,右子树最大深度中的较大值机上当前节点的深度(1)。

//root->depth
public int maxDepth(TreeNode root) {
	//递归的出口
	if(root==null){
		return 0;
	}
	//否则,不管三七二十一,去求得左子树和右子树的结果
	int left=maxDepth(root.left);
	int right=maxDepth(root.right);
	//最后,考虑left,right和整棵树的最大值之间的关系
	return Math.max(left,right)+1;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值