Leetcode刷题104. 二叉树的最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

感谢数据结构和算法的详细解法,传送门递归,BFS,DFS的3种解决方式

class Solution {

	//最大深度
	int max = 0;
	//遍历到的节点的深度
	int depth = 0;

    public int maxDepth(TreeNode root) {
//		return maxDepthI(root);
//		return maxDepthII(root);
//      return maxDepthIII(root);
        return maxDepthIIII(root);
    }

    //方法四:DFS遍历,使用两个栈,一个记录节点,一个记录节点所在的层数
    //stack中每个节点在level中都会有一个值对应,并且stack和level同时入栈和出栈
    //时间复杂度O(N),空间复杂度O(N)
    private int maxDepthIIII(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int max = 0;
        Stack<TreeNode> stack = new Stack<>();
        Stack<Integer> level = new Stack<>();
        stack.push(root);
        level.push(1);

        while (!stack.isEmpty()) {
            int temp = level.pop();
            TreeNode node = stack.pop();
            max = Math.max(max, temp);

            if (node.right != null) {
                stack.push(node.right);
                level.push(temp + 1);
            }
            if (node.left != null) {
                stack.push(node.left);
                level.push(temp + 1);
            }
        }
        return max;
    }

    //方法三:BFS遍历,定义变量记录二叉树的层数
    //时间复杂度O(N),空间复杂度O(N)
    private int maxDepthIII(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int max = 0;
        while (!queue.isEmpty()) {
            //队列存放的是当前层的所有节点
            int size = queue.size();
            while (size-- > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            max++;
        }
        return max;
    }

	//方法二:二叉树的遍历框架
	private int maxDepthII(TreeNode root) {
		traverse(root);
		return max;
	}

	//depth是当前遍历到的节点的深度,所以需要在前序位置加1,后序位置减1
	private void traverse(TreeNode root) {
		if (root == null) {
			//到达叶子结点,更新最大深度
			max = Math.max(max, depth);
			return;
		}
		depth++;
		traverse(root.left);
		traverse(root.right);
		depth--;
	}

	//方法一:递归,时间和空间复杂度O(N)
	private int maxDepthI(TreeNode root) {
		if (root == null) {
			return 0;
		}
		int leftMax = maxDepth(root.left);
		int rightMax = maxDepth(root.right);
		return Math.max(leftMax, rightMax) + 1;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值