秒杀二叉树深度

#秒杀二叉树深度

1:递归

public int maxDepth(TreeNode root) {
    return root==null?0:Math.max(maxDepth(root.left),maxDepth(root.right)) + 1; 
}

递归的思想还是很简单的,再看看第二种思想
2:非递归
这里用到了配对(Pair)。配对提供了一种方便方式来处理简单的键值关联,当我们想从方法返回两个值时特别有用。

 public int maxDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
    //pair存储节点和一个数
    Stack<Pair<TreeNode, Integer>> stack = new Stack<>();
    //把根节点入栈 value为1
    stack.add(new Pair<>(root, 1));
    int h = 0;
    while (!stack.isEmpty()) {
    //取出栈顶元素,并用Pair来存储
        Pair<TreeNode, Integer> pair = stack.pop();
        //比较pair的value值和h 
		h = Math.max(pair.getValue(), h);
		//遍历当前节点左右孩子节点
		if (pair.getKey().right != null) {
           stack.push(new Pair<>(pair.getKey().right, pair.getValue() + 1));
        }
        if (pair.getKey().left != null) {
            stack.push(new Pair<>(pair.getKey().left, pair.getValue() + 1));
        }
    }
    return h;
}

3: BFS

public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        List<TreeNode> queue = new LinkedList<>() {{ add(root); }}, tmp;
        int res = 0;
        while(!queue.isEmpty()) {
            tmp = new LinkedList<>();
            for(TreeNode node : queue) {
                if(node.left != null) tmp.add(node.left);
                if(node.right != null) tmp.add(node.right);
            }
            queue = tmp;
            res++;
        }
        return res;
    }

That’s All !

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值