题目来源

104. 二叉树的最大深度 - 力扣(LeetCode)

代码1(bfs迭代法)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int depth = 0;
        while(!queue.isEmpty()) {
            int size = queue.size(); // 当前层:结点数
            depth ++;

            for(int i = 0; i < size; i ++) {
                TreeNode node = queue.poll(); //当前层出队

                //下一层入队
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }
        }
        return depth;
    }
}

代码分析

int depth 记录当前层,深度

代码2(dfs迭代法)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;

        Stack<TreeNode> nodeStack = new Stack<>();
        Stack<Integer> depthStack = new Stack<>();

        int maxDepth = 0;
        nodeStack.push(root);
        depthStack.push(1);

        while(!nodeStack.isEmpty()) {
            TreeNode node = nodeStack.pop();
            int depth = depthStack.pop();

            maxDepth = Math.max(depth, maxDepth);
            // 先把右子树入栈,这样左子树就在栈顶了
            if(node.right!=null) {
                nodeStack.push(node.right);
                depthStack.push(depth+1);
            }
            if(node.left!=null) {
                nodeStack.push(node.left);
                depthStack.push(depth+1);
            }
        }
        return maxDepth;
    }
}

代码分析

利用栈,记录当前结点的深度。跟结点入栈同步记录该结点的深度。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐