LeetCode 104 二叉树的最大深度

二叉树的最大深度的解决,很简单的一道题。    

比如一棵树如图所示:

             3

        5       6

    2     4

7

①递归的思路 :H = 1+max((H-5),(H-6)) = 4

                      H-5 = 1+max((H-2),(H-4)) = 3

                      H-2 = 1+max((H-7),0) = 2

                      H-7 = 1+max(0,0) = 1

                      H-4 = 1+max(0,0) = 1

                      H-6 = 1+max(0,0) =  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;
        }else{
            int left_height = maxDepth(root.left);
            int right_height = maxDepth(root.right);
            return java.lang.Math.max(left_height,right_height)+1;
        }
    }
}

         ②迭代的思路:

             

class Solution{
	public int maxDepth(TreeNode root){
		Queue<Pair<TreeNode,Integer>> stack = new LinkedList<>();
		if(root != null){
			stack.add(new Pair(root,1));
		}
		int depth = 0;
		while(!stack.isEmpty()){
			Pair<TreeNode,integer> current = stack.poll();
			root = current.getKey();
			int current_depth = current.getValue();
			if(root != null){
				depth = Math.max(depth, current_depth);
				stack.add(new Pair(root.left,current_depth+1));
				sttack.add(new Pair(root.right,current_depth+1));
			}
		}
	}
}

                    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值