zoukankan      html  css  js  c++  java
  • 104. Maximum Depth of Binary Tree

    Given a binary tree, find its maximum depth.

    The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

     
    f the node does not exist, simply return 0. Otherwise, return the 1+the longer distance of its subtree.
    
    public int maxDepth(TreeNode root) {
            if(root==null){
                return 0;
            }
            return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
        }
    

      

    DFS
    
    public int maxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        
        Stack<TreeNode> stack = new Stack<>();
        Stack<Integer> value = new Stack<>();
        stack.push(root);
        value.push(1);
        int max = 0;
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            int temp = value.pop();
            max = Math.max(temp, max);
            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 max;
    }
    

      

    BFS
    
    public int maxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int count = 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);
                }
            }
            count++;
        }
        return count;
    }
    // 3ms
    

      

  • 相关阅读:
    对Promise的理解?
    对JavaScript垃圾回收机制的理解?
    说明split()与join()函数的区别?
    目标检测评估标准
    训练自己的数据集
    ssd_mobilenet_demo
    c++读取数据
    0XFF
    python读取数据
    快速排序
  • 原文地址:https://www.cnblogs.com/apanda009/p/7965149.html
Copyright © 2011-2022 走看看