104. 二叉树的最大深度

import java.util.LinkedList;
import java.util.Queue;

/**
 * 给定一个二叉树,找出其最大深度。
 * <p>
 * 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
 * <p>
 * 说明: 叶子节点是指没有子节点的节点。
 * <p>
 * 示例:
 * 给定二叉树 [3,9,20,null,null,15,7],
 * <p>
 *       3
 *      / \
 *     9  20
 *   /  \
 * 15   7
 * 返回它的最大深度 3
 * <p>
 * 来源:力扣(LeetCode)
 * 链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
 * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 */
public class MaxDepth {

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

    public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }

    public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    //广度优先算法
    public static int MaxDepthV2(TreeNode root){
        if(null == root){
            return 0;
        }
        int maxDepth = 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            while (size >0 ){
                TreeNode node = queue.poll();
                if(null != node.left){
                    queue.offer(node.left);
                }
                if(null != node.right){
                    queue.offer(node.right);
                }
                size--;
            }
            maxDepth++;
        }

        return maxDepth;
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(15);
        TreeNode treeNode2 = new TreeNode(7);
        TreeNode treeNode3 = new TreeNode(9,treeNode1,treeNode2);
        TreeNode treeNode4 = new TreeNode(20);
        TreeNode treeNode5 = new TreeNode(3,treeNode3,treeNode4);
        int maxDepth = MaxDepthV2(treeNode5);
        System.out.println("RESULT ====" + maxDepth);


    }
}

 

posted @ 2020-07-28 10:31  TPL  阅读(67)  评论(0编辑  收藏  举报