[leetcode] Maximum depth of binary tree

Find the maximum depth of a binary tree

Given a binary tree, find its maximum depth.

The depth of the binary tree is the number of nodes on the longest path from the root node to the furthest leaf node.

Explanation: A leaf node refers to a node that has no child nodes.

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

    3
   / \
  9  20
    /  
   15 
  /
 7    

Returns its maximum depth 3

1. Recursion

    public int maxDepth(TreeNode root) {
        //递归算法
        if(root == null){
            return 0;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return Math.max(left,right)+1;
    }

2. Iterative
DFS (depth first) preorder traversal

/**
     * DFS迭代实现二叉树最大深度
     * 时间复杂度O(n)
     * 空间复杂度:线性表最差O(n)、二叉树完全平衡最好O(logn)
     * 大概就是利用了栈的入栈出栈(最大两个),每次压栈,看它的左右节点有没有,有就加1,计算取深度最大值,再弹出去,它的子节点再入栈,如此循环,计算深度。
     * @param root 根节点
     * @return 最大深度
     */
    private static int maxDepth2(TreeNode root) {
         if(root == null) {
            return 0;
        }
        Stack<TreeNode> stack = new Stack<>();
        Stack<Integer> value = new Stack<>();
        stack.push(root);
        value.push(1);
        int depth = 0;
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            int temp = value.pop();
            depth = Math.max(temp, depth);
            if(node.left != null) {
                stack.push(node.left);
                value.push(temp+1);
            }
            if(node.right != null) {
                stack.push(node.right);
                value.push(temp+1);
            }
        }
        return depth;
    } 

BFS (width-first) traversal

/**
     * BFS迭代实现二叉树最大深度
     * 时间复杂度O(n)
     * 空间复杂度:线性表最差O(n)、二叉树完全平衡最好O(logn)
     * 利用队列
     * @param root 根节点
     * @return 最大深度
     */
    private static int maxDepth1(TreeNode root) {
                if(root==null) return 0;
        
        int depth = 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while( !queue.isEmpty() ){
            depth++;
            int size = queue.size();//注意,这里必须先拿到size!(size是上一层的node个数)
            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;
    }
Published 8 original articles · Like1 · Visitors 115

Guess you like

Origin blog.csdn.net/iYhuitune/article/details/105546974