leetcode-pp / 91alg-5-daily-check

91 天学算法第五期打卡
55 stars 14 forks source link

【Day 13 】2021-09-22 - 104. 二叉树的最大深度 #28

Open azl397985856 opened 3 years ago

azl397985856 commented 3 years ago

104. 二叉树的最大深度

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree

前置知识

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例: 给定二叉树 [3,9,20,null,null,15,7],

3

/ \ 9 20 / \ 15 7 返回它的最大深度 3 。

XinnXuu commented 3 years ago

思路

递归,把当前树高度的问题,分解为右子树高度和左子树高度的子问题。

代码

/**
 * 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;
        }
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

复杂度分析

Victoria011 commented 3 years ago

思路

采用 recursion 的想法,每个root深度是 left subtree, right subtree两个子数中更大深度+1;leaf node 深度是1, 不断recursion计算left, right child node深度。

代码

class Solution {
        public int maxDepth(TreeNode root) {
                if (root == null) return 0;
                if ((root.left == null) && (root.right == null)) return 1;

                int max_depth = Integer.MIN_VALUE;
                if (root.left != null) {
                        max_depth = Math.max(maxDepth(root.left), max_depth);
                }
                if (root.right != null) {
                        max_depth = Math.max(maxDepth(root.right), max_depth);
                }
                max_depth++;
                return max_depth;
        }
}

复杂度分析

lxy030988 commented 3 years ago

思路

代码 js

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function (root) {
  if (root == null) {
    return 0
  }
  return Math.max(1 + maxDepth(root.left), 1 + maxDepth(root.right))
}

复杂度分析

15691894985 commented 3 years ago

Day 13 二叉树的最大深度

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree

思路:

chenming-cao commented 3 years ago

解题思路

递归,递归出口是root == null,此时最大深度为0。其余条件下比较左右子树的最大深度,取较大者+1。

代码

/**
 * 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;
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

复杂度分析

JunQu commented 3 years ago

思路

使用深度优先对我理解比较友好,于是直接使用深度优先的方法递归左/右子树的深度。

代码实现

const maxDepth = function(root) {
    if(!root) {
        return 0;
    }
    return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
};

复杂度分析

时间复杂度: O(n), 需要遍历整个树的元素 空间复杂度: O(h), h为二叉树的高度,递归调用栈需要最大的空间就是它的高度。

shixinlovey1314 commented 3 years ago

Title:104. Maximum Depth of Binary Tree

Question Reference LeetCode

Solution

We can use DFS, goes all the way to the leaf, the depth of leaf node is 1. Then bottom up, for each node, its hight is max(left, right) + 1.

Code

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root)
            return 0;

        int l = maxDepth(root->left);
        int r = maxDepth(root->right);

        return max(l, r) + 1;
    }
};

Complexity

Time Complexity and Explaination

O(n), we need to at least visit each node once

Space Complexity and Explaination

O(logn), the size of the recursion stack, worst case will be O(n), when the tree is a skewed tree

carterrr commented 3 years ago

class 二叉树的最大深度_104 { public int maxDepth(TreeNode root) { return maxDepth_cursive(root, 0); }

private int maxDepth_cursive(TreeNode root, int depth) {
    if(root == null) return depth;
    int leftDepth = maxDepth_cursive(root.left, depth + 1);
    int rightDepth = maxDepth_cursive(root.right, depth + 1);
    return Math.max(leftDepth, rightDepth);
}

}

carsonlin9996 commented 3 years ago

DFS

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

xy147 commented 3 years ago

思路

递归

js代码

var maxDepth = function (root) {
  if (root === null) {
    return 0;
  }
  return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};

复杂度分析

ZJP1483469269 commented 3 years ago

思路

递归

代码

class Solution {
public int maxDepth(TreeNode root) {
    if(root==null)return 0;
    TreeNode l = root.left;
    TreeNode r = root.right;
    return Math.max(maxDepth(l),maxDepth(r))+1;
}
}

复杂度分析

时间复杂度:O(N) 空间复杂度:O(h)

ningli12 commented 3 years ago

思路

recursion

代码

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

复杂度

时间复杂度:O(n) 空间复杂度:O(n)

leolisgit commented 3 years ago

思路

考察二叉树的遍历。利用递归的思想,如果已知左子树深度,以及右子树深度,那么该节点的最大深度就是当中的最大值+1。 递归终止条件就是节点为空,深度为0。

代码

class Solution {
    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;
    }
}

复杂度

时间:O(n)
空间:O(h)

AgathaWang commented 3 years ago

二叉树

# python
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0
        return max(self.maxDepth(root.left),self.maxDepth(root.right))+1

时间复杂度: O(N)

doveshnnqkl commented 3 years ago

思路

深度优先,每次遍历到下一层计数器加1,比较计数器与返回值的大小,取大的数重新赋值,退回上一层计数器-1

代码

java

class Solution {
    int count = 0;
    public int maxDepth(TreeNode root) {
        if(root == null){
            return count;
        }
        ++count;
        dfs(root,count);
        return count;
    }

    private void dfs(TreeNode root,int max){
        if(root.right == null && root.left == null ){
            return;
        }
        max += 1;
        count = Math.max(count,max);
        if(root.right == null){
            dfs(root.left,max);
            max--;
            return;
        }
         if(root.left == null){
            dfs(root.right,max);
             max--;
            return;
        }
            dfs(root.left,max);
            dfs(root.right,max);
            max--;

    }
}

复杂度

时间复杂度:O(n) 空间复杂度:O(h)

linearindep commented 3 years ago

【思路】 dfs;实现方式:递归。 把depth传下去,到了leaf就return回来,比较左右节点最高的depth,return大的那一个 【复杂度】O(n)每个节点只过了一遍

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        return helper(root,0);
    }

    public int helper(TreeNode temp, int depth){
        if(temp == null){
            return depth;
        }

        int left_d = helper(temp.left,depth+1);
        int right_d = helper(temp.right, depth+1);

        return Math.max(left_d,right_d);
    }
}
QiZhongdd commented 3 years ago

var maxDepth = function(root) { if(!root){ return 0 } return 1+Math.max(maxDepth(root.left),maxDepth(root.right)) };

复杂度:时间O(n),空间O(n)

simonsayshi commented 3 years ago
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL)
            return 0;
        int left = maxDepth(root->left);
        int right = maxDepth(root->right);
        return max(left, right) + 1;
    }
};
Socrates2001 commented 3 years ago

C implementation

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

int max(int a, int b)
{
    if(a > b)
        return a;
    else
        return b;
}
int maxDepth(struct TreeNode* root){
    if(root == NULL)
        return 0;
    else 
        return max(maxDepth(root->left), maxDepth(root->right) ) + 1;      
}
shuichen17 commented 3 years ago
/*Time complexity: O(N)
  Space complexity: O(N) depends queue size
*/
var maxDepth = function(root) {

    let count = 0;
    if (root === null) return count;
    let queue = [];
    queue.push(root);
    while (queue.length !== 0) {
        let len = queue.length;
        for (let i = 0; i < len; i++) {
            let node = queue.shift();
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }
        count++;
    }
    return count;
};
hwpanda commented 3 years ago
const maxDepth = (root) => {
    let max = 0;

    const helper = (root, i) => {
        if (!root) return 0;

        max = Math.max(i + 1, max);

        helper(root.left, i + 1);
        helper(root.right, i + 1);
    };
    helper(root, 0);
    return max;
};
TimmmYang commented 3 years ago

思路

DFS,子问题是求左右两个子树的最大深度。

代码

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        def dfs(node):
            if not node:
                return 0
            maxleft = dfs(node.left)
            maxright = dfs(node.right)
            return max(maxleft, maxright) + 1
        return dfs(root)

复杂度

时间:O(N) N为二叉树节点数 空间:O(H) H为二叉树的高度

m-z-w commented 3 years ago
var maxDepth = function(root) {
    if (root === null) return 0
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
};

时间复杂度:O(n) 空间复杂度:O(h),h为二叉树的高度

jinmenghan commented 3 years ago

题目地址()

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

题目描述

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。

前置知识

思路

用递归思路求出左树的深度

maxDepth(root.left) + 1 ,加上1 代表子树的深度,加上本身

代码

Java Code:


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

复杂度分析

令 n 为数组长度。

a244629128 commented 3 years ago

var maxDepth = function(root) {
    if(!root) return 0;
    let left = maxDepth(root.left);
    let right = maxDepth(root.right);
    return Math.max(left,right)+1;
};
//时间复杂度:$O(n)$
//空间复杂度:$O(H)$ 树的深度
Awenbocc commented 3 years ago

思路

dfs

代码

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        self.depth = 1

        def dfs(node,cur):

            if not node:
                return 

            if cur>self.depth:
                self.depth =cur

            dfs(node.left,cur+1)
            dfs(node.right,cur+1)

        dfs(root,self.depth)

        return self.depth

复杂度分析

xyinghe commented 3 years ago

二叉树的最大深度

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

思路

DFS.检查root是否为空,比较左右子树深度,最大深度为+1

代码
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }else{
            int leftHeight = maxDepth(root.left);
            int rightHeight = maxDepth(root.right);
            return Math.max(leftHeight,rightHeight) + 1;
        }
    }
}
LareinaWei commented 3 years ago

Thinking

Recursively find out the depth on both left and right subtrees, then the depth of the node is the bigger one of the two depths.

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

Complexity

Time complexity: O(n). Since every node needs to be reached.
Space complexity: O(h).

Zhi22 commented 3 years ago

思路一

递归法:以当前节点为根节点的树的最大高度等于max(左子树高度,右子树高度)+ 1

代码

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        def helper(root: TreeNode):
            if not root:
                return 0
            return 1 + max(helper(root.left), helper(root.right))
        return helper(root)

算法复杂度

思路二

迭代法:层序遍历,每遍历到新的一层就把返回值加一

代码

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        stack = []
        def BFS(root: TreeNode):
            if root: stack.append(root)
            else: return 0
            height = 0
            while stack:
                height += 1
                sz = len(stack)
                for _ in range(sz):
                    curr = stack.pop(0)
                    if curr.left: stack.append(curr.left)
                    if curr.right: stack.append(curr.right)
            return height
        return BFS(root)

算法复杂度

kennyxcao commented 3 years ago

104. Maximum Depth of Binary Tree

Intuition

Code

/**
 * @param {TreeNode} root
 * @return {number}
 */
const maxDepth = function(root) {
  if (!root) return 0;
  return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};

Complexity Analysis

septasset commented 3 years ago

思考

关键点

代码(Python)

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root is None: return 0
        return 1+max(self.maxDepth(root.left), self.maxDepth(root.right))

复杂度分析

lihanchenyuhua commented 3 years ago

class Solution { public: int maxDepth(TreeNode* root) { if (root == nullptr) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } };

Bochengwan commented 3 years ago

思路

通过BFS的层序遍历来得到树的高度。

代码

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        stack = [root]
        ans=0
        while stack:
            n = len(stack)
            for _ in range(n):
                curr = stack.pop(0)
                if curr.left:
                    stack.append(curr.left)
                if curr.right:
                    stack.append(curr.right)
            ans+=1
        return ans

复杂度分析

zszs97 commented 3 years ago

开始刷题

题目简介

【Day 13 】2021-09-122 - 104. 二叉树的最大深度

方法一

方法二

题目代码

方法一

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        return max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};

方法二

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        queue<TreeNode*> Q;
        Q.push(root);
        int ans = 0;
        while (!Q.empty()) {
            int sz = Q.size();
            while (sz > 0) {
                TreeNode* node = Q.front();Q.pop();
                if (node->left) Q.push(node->left);
                if (node->right) Q.push(node->right);
                sz -= 1;
            }
            ans += 1;
        } 
        return ans;
    }
};

复杂度

方法一

方法二

DoubleW2w commented 3 years ago

思路1:DFS

递归:

  1. 递归函数定义:入参是根节点,返回值是树的最大深度
  2. 递归终止条件:当节点为空,返回0
  3. 单层递归逻辑:节点不为空时,求左子树和右子树的最大深度

代码

Java Code:

/**
 * 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 {
    //递归
    //函数定义:入参是跟节点,返回值是树的最大深度
    //递归终止:节点为空,返回0
    //递归逻辑;求树的最大深度
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        else{
            int left = maxDepth(root.left);
            int right = maxDepth(root.right);
            return Math.max(left,right) + 1;
        }
    }
}

复杂度分析

令 n 为二叉树节点数。

思路2:BFS

因为要求最大深度,跟层序遍历的逻辑是一样的。

代码

Java Code:

class Solution {
    public int maxDepth(TreeNode root) {
        int depth = 0;
        Deque<TreeNode> deque = new ArrayDeque<>();
        if(root == null) return depth;
        deque.offer(root);
        while(!deque.isEmpty()){
            int size = deque.size();
            for(int i = 0; i < size; i++){
                TreeNode node = deque.poll();
                if(node.left != null) deque.offer(node.left);
                if(node.right != null) deque.offer(node.right);
            }
            depth++;
        }
        return depth;
    }
}

复杂度分析

令 n 为二叉树节点数。

xiaowenhe commented 3 years ago
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root is None:
            return 0
        return max(self.maxDepth(root.left),self.maxDepth(root.right)) + 1
ru8dgj0001 commented 3 years ago

“ class Solution: def maxDepth(self, root): if not root: return 0 else: return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) ”

Laurence-try commented 3 years ago

思路

I used BFS for this question. First, I created a parents list with appending the root (of course, while we have the root, if not, return 0 instead). Then, I created another list to store the whole tree. Then, I appended the parents list (now only with the root) to the tree, to show at this moment, the tree had one depth. After this, we can enter the iterations. At the beginning of each iteration, I created an empty list to store the parents' children. For all the parent in parents list, I searched its children (whether it has left child or right child), if it had children, append them to the new created children list. While finishing searching for all the parent in the parents list, which means I found all the node in the next depth. At this moment, I append this children list to the tree, after that I let this children list be parents list to start another iteration. While we cannot find any children from the last all parents list, I reached the most deep of the tree. And then, I can directly return the length of the tree for the answer. To be notice that, while search the farthest node, its None left and right node was added to the tree, so I need to return the len(tree) - 1 to get the final answer.

代码

使用语言:Python3

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root:
            parents = []
            parents.append(root)
            tree = [parents]
            while parents:
                children = []
                for parent in parents:
                    if parent.left:
                        children.append(parent.left)
                    if parent.right:
                        children.append(parent.right)
                tree.append(children)
                parents = children
            return len(tree) - 1
        return 0

复杂度分析 时间复杂度:O(N) 空间复杂度:O(N)

L-SUI commented 3 years ago

var maxDepth = function(root) { if(!root) { return 0; } else { const left = maxDepth(root.left); const right = maxDepth(root.right); return Math.max(left, right) + 1; } };

ff1234-debug commented 3 years ago

思路: 递归

* root为空时返回0,最终树的高度为左子树和右子树高度的最大值加1   

C++代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root)
    {
      if(root==nullptr) return 0;
      int left=maxDepth(root->left);
      int right=maxDepth(root->right);
      return left>right?left+1:right+1;
    }
};

复杂度分析

Huangxuang commented 3 years ago

题目:104. Maximum Depth of Binary Tree

思路

代码

/**
 * 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;
        }

        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);

        return Math.max(leftDepth, rightDepth) + 1;
    }

}

复杂度分析

RonghuanYou commented 3 years ago
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root is None: return 0;    

        left = self.maxDepth(root.left);
        right = self.maxDepth(root.right);

        return max(left, right) + 1;
Okkband commented 3 years ago
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        return max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};

时间复杂度:O(N), N为二叉树节点的个数

空间复杂度:O(N)

chaggle commented 3 years ago

Day-13 :2021-09-22

104. 二叉树的最大深度

题目

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。

题目思路

代码块。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        /* if (root == nullptr) return 0;
        int l, r;
        l = maxDepth(root -> left);
        r = maxDepth(root -> right);
        return一些 max(l, r) + 1; */
        //以下为BFS
        queue<TreeNode* > q;
        if (root == nullptr) return 0;
        q.push(root);
        int tmp = 0;
        while(q.empty() == 0)
        {
            int n = q.size();
            tmp++;
            for(int i = 0; i < n; i++)
            {
                TreeNode* res = q.front();
                q.pop();
                if(res -> left != nullptr) q.push(res -> left);
                if(res -> right != nullptr) q.push(res -> right);
            }
        }
        return tmp;
    }
};

复杂度

jaysonss commented 3 years ago

思路

代码

深度优先:
  public int maxDepth(TreeNode root) {
        if(root == null)return 0;
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return Math.max(leftDepth,rightDepth) + 1;
    }
广度优先:
  public int maxDepth(TreeNode root) {
        if(root == null)return 0;
        int dep = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ans = 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);
                }
                size--;
            }
            ans++;
        }
        return ans;
    }

复杂度

kofzhang commented 3 years ago
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: TreeNode) -> int:

        def dfs(node,depth):
            if not node:
                return depth
            return max(dfs(node.left,depth+1),dfs(node.right,depth+1))
        res = dfs(root,0)
        return res
q815101630 commented 3 years ago
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        return 1+max(self.maxDepth(root.left), self.maxDepth(root.right))
yyangeee commented 3 years ago

104

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

思路

层序遍历,每一层遍历完计数器+1

学到的语法

代码

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        queue = [root]
        n = 0

        while queue:
            length = len(queue)  
            for _ in range(length):
                curnode = queue.pop(0) 
                if curnode.left: 
                    queue.append(curnode.left)
                if curnode.right: 
                    queue.append(curnode.right)
            n += 1    
        return n

复杂度

minuet-red commented 3 years ago

时间复杂度 O(n) 空间复杂度 O(n)

class Solution {
public:
    int res = 0;
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;

        int left = maxDepth(root->left);
        int right = maxDepth(root->right);

        return 1 + max(left, right);
        //return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
};
pandaCure commented 3 years ago

思路

树的最大深度 = 左子树最大深度与右子树最大深度最大深度 + 1

代码

function maxDepth(root: TreeNode | null): number {
  if (root === null) return 0;
  return Math.max(maxDepth(root.left) , maxDepth(root.right)) + 1;
}

复杂度

时间:O(n) 空间:O(n)