zoukankan      html  css  js  c++  java
  • [GeeksForGeeks] Find the maximum depth or height of a tree

    Given a binary tree, find the maximum depth or height of this tree.

    Solution 1. In order traversal to count the maximum depth

     1 import java.util.LinkedList;
     2 import java.util.Queue;
     3 
     4 class TreeNode {
     5     TreeNode left;
     6     TreeNode right;
     7     int val;
     8     TreeNode(int val){
     9         this.left = null;
    10         this.right = null;
    11         this.val = val;
    12     }
    13 }
    14 public class Solution {
    15     public int findMaxDepth(TreeNode root) {
    16         if(root == null){
    17             return 0;
    18         }
    19         Queue<TreeNode> queue = new LinkedList<TreeNode>();
    20         int maxDepth = 0;
    21         queue.offer(root);
    22         while(!queue.isEmpty()){
    23             int size = queue.size();
    24             for(int i = 0; i < size; i++){
    25                 TreeNode curr = queue.poll();
    26                 if(curr.left != null){
    27                     queue.offer(curr.left);
    28                 }
    29                 if(curr.right != null){
    30                     queue.offer(curr.right);
    31                 }
    32             }
    33             maxDepth++;
    34         }
    35         return maxDepth;
    36     }
    37 }

    Solution 2. Recursion on both left and right subtree.

     1 class TreeNode {
     2     TreeNode left;
     3     TreeNode right;
     4     int val;
     5     TreeNode(int val){
     6         this.left = null;
     7         this.right = null;
     8         this.val = val;
     9     }
    10 }
    11 public class Solution {
    12     public int findMaxDepth(TreeNode root) {
    13         if(root == null){
    14             return 0;
    15         }
    16         int leftDepth = findMaxDepth(root.left);
    17         int rightDepth = findMaxDepth(root.right);
    18         return leftDepth > rightDepth ? 1 + leftDepth : 1 + rightDepth;
    19     }
    20 }

    Both solution 1 and 2's runtime are O(n), n is the total number of nodes in the given binary tree. 

    Solution 1 uses O(n) extra memory for the queue used, where solution 2 only uses O(1) memory 

    for each recursive call. But the downside of the recursive solution is the the methods stack may

    get very deep.

  • 相关阅读:
    windows通过Composer安装yii2
    jquery自定义函数
    js 回调
    读取.properties配置文件
    spring @ModelAttribute 注解
    excel导出
    spring定时器
    maven添加自己的jar包到本地仓库
    activeMq 消费者整合spring
    linux操作命令
  • 原文地址:https://www.cnblogs.com/lz87/p/7302650.html
Copyright © 2011-2022 走看看