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 。

Tomtao626 commented 3 years ago

思路

  • DFS

    代码

    class Solution:
    def maxDepth(self, root):
    if root is None: 
    return 0 
    else: 
    left_height = self.maxDepth(root.left) 
    right_height = self.maxDepth(root.right) 
    return max(left_height, right_height) + 1 

    复杂度

  • 时间:O(n)
  • 空间:O(height)
wangzehan123 commented 3 years ago

代码

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 {
    public int maxDepth(TreeNode root) {
        if(null == root){
            return 0;
        }
        return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    }
}

复杂度分析

令 n 为数组长度。

yanglr commented 3 years ago

思路:

可以用递归处理, 也可以使用层次遍历将每层的值放进二维数组中, 最后看二维数组的size是多少。

方法1: 递归

递归做的话,如果root == NULL, 直接返回0。否则看左子树的最大深度是多少,右子树的最大深度是多少,最后取较大者+1,+1是因为root的深度是1。

C++代码:

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

复杂度分析

方法2: 层次遍历(BFS)

C++代码:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        queue<TreeNode*> q;
        q.push(root);
        vector<vector<int>> levels;
        while (!q.empty())
        {
            vector<int> curLevel;
            for (int i = q.size(); i > 0; i--)
            {
                auto p = q.front();
                curLevel.push_back(p->val);
                q.pop();
                if (p->left != nullptr) q.push(p->left);
                if (p->right != nullptr) q.push(p->right);
            }
            levels.push_back(curLevel);
        }
        return levels.size();
    }
};

复杂度分析

xj-yan commented 3 years ago
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        int[] maxDepth = {0};
        traverseTree(root, maxDepth);
        return maxDepth[0];
    }

    private int traverseTree(TreeNode root, int[] maxDepth){
        if (root == null) return 0;

        int left = traverseTree(root.left, maxDepth), right = traverseTree(root.right, maxDepth);
        int depth = Math.max(left, right) + 1;
        maxDepth[0] = Math.max(maxDepth[0], depth);
        return depth;
    }
}

Time Complexity: O(n) Space Complexity: O(h) -> Worst Case Scenario: O(n)

okbug commented 3 years ago

思路

递归,终止条件是为叶子结点,返回0,那么每个节点都去比较自己的左和右节点,就可以得到结果

代码

JavaScript

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

C++

class Solution {
public:
    int maxDepth(TreeNode* root) {
        return root ? max(maxDepth(root->left), maxDepth(root->right)) + 1 : 0;
    }
};
BreezePython 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))

复杂度

ivalkshfoeif commented 3 years ago
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return Math.max(maxDepth(root.right), maxDepth(root.left)) + 1;

    }
}

经典递归

HarleysZhang commented 3 years ago

解题方法

1,递归法

class Solution {
public:
    // 递归法
    int maxDepth(TreeNode* root) {
        if(root){
            return 1 + max(maxDepth(root -> left), maxDepth(root -> right));
        }
        else{
            return 0;
        }

    }
};
BpointA commented 3 years ago

思路

递归,出口为空结点,每层高度+1。

Python3代码

# 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:
        if root==None:
            return 0
        else:
            a=self.maxDepth(root.left)
            b=self.maxDepth(root.right)
            return 1+max(a,b)            

复杂度

时间复杂度:O(n) 相当于遍历整个树

空间复杂度:O(logn) 需比较的常数的数量级与二叉树的高度成正比

yibenxiao commented 3 years ago

104. 二叉树的最大深度

思路

深度遍历

代码

# 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:
        if root:
            return (1+max(self.maxDepth(root.left),self.maxDepth(root.right))) 
        return 0

复杂度

时间复杂度:O(N)

空间复杂度:O(N)

Menglin-l commented 3 years ago

思路:

1.base case: root为null

2.最大深度为左右子树的最大深度+1,因为root也算一层


代码部分:

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

复杂度:

Time: O(N)

Space: O(height),树的高度

thinkfurther commented 3 years ago

思路

递归左右节点,返回最大值

代码

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:

        if root == None:
            return 0

        leftDepth = self.maxDepth(root.left)
        rightDepth = self.maxDepth(root.right)

        return max(leftDepth, rightDepth) + 1

复杂度

时间复杂度 :O(n)

空间复杂度:O(h)

mm12344 commented 3 years ago

思路

递归: 以当前节点为根目录的树的最大深度为该问题的子问题 构建子问题和母问题的关系等式 确定终止条件:若结点自身为空,则返回0,该层为空(即输入中的null,空节点-终止条件与自身有关,无需考虑左右子树)

代码


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

复杂度

时间:O(n), n为非空节点个数 空间:O(maxdepth),因为递归的每一层输出都要先放在缓存里,所以最坏情况maxdepth=n

ginnydyy commented 3 years ago

Problem

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

Notes

Solution

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

}

Complexity

jsyxiaoba 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) return 0;

    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right))
};

// 广度遍历
var maxDepth = function(root) {
    if(!root) return 0;
    let queue = [root];
    let count = 0;
    while(queue.length > 0){
        let len = queue.length;
        while(len--){ // 把当前层级的queue队列清空,同时把左右子节点push进队列
            let f = queue.shift(); // 左出
            if(f.left) queue.push(f.left); // 左子节点入队列
            if(f.right) queue.push(f.right); // 右子节点入队列
        }
        count++
    }
    return count
};

复杂度

st2yang commented 3 years ago

思路

代码

复杂度

erik7777777 commented 3 years ago

思路

post order traverse and get answer from left node and right node recursion function is : Math.max(leftAns, rightAns) + 1

代码

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

复杂度 time: O(n) space: O(n) -> depth of stack. worst case is when tree is a linkedlist

hengistchan commented 3 years ago

代码

 const maxDepth = function (root) {
    let queue = [], res = 0;
    if (root == null) return res;

    queue.push(root)

    while (queue.length) {
      let tmp = queue.length
      while (tmp--) {
        const sf = queue.shift()
        if (sf.left) {
          queue.push(sf.left)
        }
        if (sf.right) {
          queue.push(sf.right)
        }
      }
      res++
    }
    return res
  };
cicihou 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:
        if not root:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
fzzfgbw commented 3 years ago

思路

递归

代码

func maxDepth(root *TreeNode) int {
    if root == nil {
        return 0
    } else {
        left := maxDepth(root.Left)
        right := maxDepth(root.Right)
        if left > right {

            return 1 + left
        } else {
            return 1 + right
        }
    }
}

复杂度分析

Mahalasu commented 3 years ago

思路

recursion

# 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

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

T: O(n) S: O(logn)

JiangyanLiNEU commented 3 years ago

Idea

DFS: return 1 + max(left, right)

Implement

class Solution(object):
    def maxDepth(self, root):
        # stop condition
        if not root:
            return 0
       # get the max depth of left child and right child -- same problem
        left = self.maxDepth(root.left)
        right = self.maxDepth(root.right)
       # return the maximum
        return 1 + max(left, right)
potatoMa commented 3 years ago

思路1


广度优先搜索BFS

代码


JavaScript Code

/**
 * 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) return 0;
    const rootStack = [[root]];
    let index = 0, temp = [];
    function countDeep() {
        temp = [];
        for (const leaf of rootStack[index]) {
            if (leaf.left) temp.push(leaf.left);
            if (leaf.right) temp.push(leaf.right);
        }
        if (temp.length) {
            index++;
            rootStack.push(temp);
            countDeep();
        }
    }
    countDeep();
    return index + 1;
};

复杂度分析


时间复杂度:O(N)

空间复杂度:O(N)

思路2


深度优先搜索DFS

代码


JavaScript Code

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

复杂度分析


时间复杂度:O(N)

空间复杂度:O(height),递归函数需要的空间取决于树的高度

yachtcoder commented 3 years ago

Use a DFS to do the counting of a node it visits. Time: O(n) Space: O(n)

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

思路

递归,最大深度为max(l,r)+1

代码

var maxDepth = function(root) {
    if(!root) return 0;
    let l = maxDepth(root.left);
    let r = maxDepth(root.right);
    return Math.max(l,r)+1
};
nonevsnull commented 3 years ago

思路

AC

AC

代码

//bfs
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;

        Queue<TreeNode> q = new LinkedList<>();

        q.add(root);

        int depth = 0;

        while(!q.isEmpty()){
            depth++;
            int size = q.size();
            for(int i = 0;i < size;i++){
                TreeNode node = q.poll();
                if(node.left != null) q.add(node.left);
                if(node.right != null) q.add(node.right);
            }
        }

        return depth;
    }
}

//dfs, 可以简化为几行剪短代码,选择保留以看得清结构
class Solution {
    public int maxDepth(TreeNode root) {
        return dfs(root, 1);
    }

    /*
        param: root, depth
        stop: root == null
        return: depth
    */

    public int dfs(TreeNode root, int depth){
        if(root == null) return depth - 1;

        int left = dfs(root.left, depth+1);
        int right = dfs(root.right, depth+1);

        return Math.max(left, right);
    }
}

复杂度

bfs time: 要遍历每一个node,因此时间复杂度O(N) space: 需要维护一个q,这个q的大小由每一层的最多的node个数决定。 2^0 + 2^1 + 2^2 + ... + 2^k = N, where k+1是层数。 根据求和公式,(2^(k+1) - 1)/(2 - 1) = N, 因此k = logN - 1,于是最后一层元素最多可能有N/2个node。 因此维护这个q需要O(N)的空间。

dfs time: 虽然递归只进行了logN次,但是每个node依旧被遍历到了,因此时间复杂度还是O(N) space: 维护递归stack的空间,由递归的层数决定,因此为O(logN);

zjsuper commented 3 years ago

Idea: recursion time O(N)

# 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 root == None:
            return 0
        deep = 1
        return max((deep+self.maxDepth(root.left)),(deep+self.maxDepth(root.right)))
falconruo commented 3 years ago

思路:

  1. 迭代(Iterative): level order遍历二叉树,使用一个队列存放每层的子节点
  2. 递归(Recursive): 根节点的深度 = 左右子树的深度的最大值+1

复杂度分析:

  1. 时间复杂度: O(n), n为树的节点数
  2. 空间复杂度: O(n), n为递归栈空间; 迭代时队列空间最大空间O(k), k为单层最大节点数

代码(C++):


// Iterative
/**
 * 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) return 0;

        int dep = 0;

        queue<TreeNode*> qt;
        qt.push(root);

        while (!qt.empty()) {
            size_t num = qt.size();
            while (num--) {
                TreeNode* node = qt.front();
                qt.pop();

                if (node->left)
                    qt.push(node->left);
                if (node->right)
                    qt.push(node->right);
            }
            ++dep;
        }
        return dep;
    }
};

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

        int dep = max(maxDepth(root->left), maxDepth(root->right)) + 1;

        return dep;
    }
};
heyqz commented 3 years ago

代码

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

复杂度

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

leo173701 commented 3 years ago

BFS 层序遍历即可

def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        dq = deque([root])
        depth =  0
        while dq:
            n = len(dq)
            for _ in range(n):
                cur = dq.popleft()
                if cur.left:
                    dq.append(cur.left)
                if cur.right:
                    dq.append(cur.right)
            depth+=1
        return depth
weichuliao commented 3 years ago

Main Idea

DFS while practice to use recursion

Code with Python

def maxDepth(self, root: Optional[TreeNode]) -> int:
    if not root:
        return 0
    return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

Complexity Analysis

leungogogo commented 3 years ago

LC104. Maximum Depth of Binary Tree

Method 1. Recursion

Main Idea

If root == null, then the depth is 0, else depth = max{left, right} + 1.

Code

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

Complexity Analysis

Time: O(n)

Space: O(height) = O(n), stack space.

Method 2. Iteration - BFS

Main Idea

In method 1, we use recursion and all the function call frames are stored in stack space, which might cause stack overflow if n is large.

We can use iteration to solve this problem and avoid using stack space. First we can use BFS to find the depth of the tree, traverse the tree by layer, and the depth of the last layer will be the depth of the tree.

Code

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

Complexity Analysis

Time: O(n).

Space: O(n), heap space.

Method 3. Iteration - DFS

Main Idea

Though it is less intuitive, we can use iterative DFS to solve this problem. This is like an in-order traversal, we need to use a stack to store information (TreeNode, Depth). If we reach the bottom of the tree, the stack top will be the next node to traverse, we can get its node and depth from the stack.

Code

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        Deque<Pair<TreeNode, Integer>> stack = new ArrayDeque<>();
        int maxDep = 1, curDep = 1;
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            // If the current node is null, get the next one from stack.
            while (!stack.isEmpty() && cur == null) {
                Pair<TreeNode, Integer> p = stack.pop();
                cur = p.getKey().right;
                curDep = p.getValue() + 1;
            }

            if (cur == null) break;

            maxDep = Math.max(maxDep, curDep);
            stack.push(new Pair<>(cur, curDep));
            cur = cur.left;
            ++curDep;
        }
        return maxDep;
    }
}

Complexity Analysis

Time: O(n)

Space: O(h) = O(n), heap space

zol013 commented 3 years ago

思路:用stack记录root和depth,pop 当前的root然后push (root.left, depth + 1) 和(root.right, depth + 1) 最后返回depth Python 3 code:

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        stack = []
        if root:
            stack.append((1, root))
        depth = 0
        while stack:
            cur_depth, node = stack.pop()
            if node:
                depth = max(depth, cur_depth)
                stack.append((cur_depth + 1, node.left))  
                stack.append((cur_depth + 1, node.right))
        return depth

time complexity : O(n) space complexity: best case: tree is balanced: O(log(n) worst case: totally unbalanced tree: O(n)

zhiyuanpeng commented 3 years ago
class Solution:

    def maxDepthHelper(self, root, max_dep):
        if root:
            l_max = self.maxDepthHelper(root.left, max_dep + 1)
            r_max = self.maxDepthHelper(root.right, max_dep + 1)
            return max(l_max, r_max)
        return max_dep 

    def maxDepth(self, root: Optional[TreeNode]) -> int:
        return self.maxDepthHelper(root, 0)

time: O(n) space: 'O(logn)'

pophy commented 3 years ago

Max Depth of binary tree

思路

Java Code

public int maxDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }

    Queue<TreeNode> queue = new LinkedList();
    queue.add(root);
    int res = 0;
    while (!queue.isEmpty()) {
        int size = queue.size();
        for (int i=0; i<size; i++) {
            TreeNode current = queue.poll();
            if (current.left != null) {
                queue.add(current.left);
            }
            if (current.right != null) {
                queue.add(current.right);
            }                
        }
        res++;
    }
    return res;
}

时间 & 空间

RocJeMaintiendrai commented 3 years ago

题目

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

思路

左右子树递归即可。

代码

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

复杂度分析

时间复杂度

O(n)

空间复杂度

O(n)

kidexp commented 3 years ago

thoughts

标准dfs 求深度

code

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        """
        recursive
        """
        max_depth = 0

        def dfs(node, level):
            if node:
                nonlocal max_depth
                max_depth = max(max_depth, level)
                if node.left:
                    dfs(node.left, level + 1)
                if node.right:
                    dfs(node.right, level + 1)

        dfs(root, 1)
        return max_depth

Complexity

时间复杂度O(n)

空间复杂度O(h),h为树的高度

pan-qin commented 3 years ago

idea: recursion the left and right subtree, find the max of the depth of left and right subtree, plus one time: O(n) space: O(h)

class Solution {

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

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

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

    max = Math.max(max, left + right);

    return Math.max(left, right) + 1;

}

} 时间复杂度O(n)

空间复杂度O(h),h为树的高度

yingliucreates commented 3 years ago

link:

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

代码 Javascript

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

复杂度分析

时间: O(N)? 空间: O(N)?

tongxw commented 3 years ago

思路

如果根节点为空,高度为0,否则高度为左右子树高度最大值+1.

代码

/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    if (root === null) {
      return 0;
    } else {
      return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
};
zhangzz2015 commented 3 years ago

思路

关键点

代码

C++ Code:

class Solution {
public:
    int ret =0; 
    int maxDepth(TreeNode* root) {

        help(root, 0);
        return ret; 
    }

    void help(TreeNode* root, int level)
    {
        if(root==NULL)
            return; 

        ret = max(ret, level+1); 
        help(root->left, level+1);
        help(root->right, level+1);
    }
};
class Solution {
public:
    int maxDepth(TreeNode* root) {

    int ret =0;         
    vector<pair<TreeNode*, int>> stack;  // use stack to record treeNode and level. 

    if(root ==NULL)
        return ret; 
    stack.push_back(make_pair(root, 1)); 
    while(stack.size())    
    {
        pair<TreeNode*, int> topNode = stack.back(); 
        stack.pop_back();
        int level = topNode.second;
        ret = max(ret, level); 

        if(topNode.first->left)
        {
            stack.push_back(make_pair(topNode.first->left, level+1));
        }
        if(topNode.first->right)
        {
            stack.push_back(make_pair(topNode.first->right, level+1));
        }
    }
    return ret; 

    }
};
biancaone commented 3 years ago

思路 🏷️

递归,取左右中的最大值


代码 📜

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        self.res = 0
        self.helper(root, 1)
        return self.res

    def helper(self, root, height):
        if root is None:
         return

        self.res = max(self.res, height)
        self.helper(root.left, height + 1)
        self.helper(root.right, height + 1)

复杂度 📦

BlueRui commented 3 years ago

Problem 104. Maximum Depth of Binary Tree

Algorithm

Complexity

Code

Language: Java

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

思路

Solution 1: Using BFS

Solution 2: Using DFS

代码

Solution 1

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        level=0
        if not root:
            return level
        bfs=collections.deque([root])
        while bfs:
            level_size=len(bfs)
            level+=1
            for _ in range(level_size):
                node=bfs.popleft()
                if node.left:
                    bfs.append(node.left)
                if node.right:
                    bfs.append(node.right)
        return level

Solution 2

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

复杂度

Time: O(n)

Space: O(n)

ghost commented 3 years ago

题目

  1. Maximum Depth of Binary Tree

思路

DFS

代码

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:

        if not root: return 0

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

复杂度

Space: O(N) Time: O(N)

mmboxmm commented 3 years ago

思路

Recursive

代码

fun maxDepth(root: TreeNode?): Int = root?.let { maxOf(maxDepth(it.left), maxDepth(it.right)) + 1 } ?: 0

复杂度

florenzliu commented 3 years ago

Explanation

Python

# 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

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

# Approach 2
class Solution:
    def maxDepth(self, root: TreeNode) -> int: 
        stack = [(root,1)]
        maxDepth = 0
        while stack:
            node, depth = stack.pop()
            if node:
                maxDepth = max(maxDepth, depth)
                stack.append((node.left, depth+1))
                stack.append((node.right, depth+1))

        return maxDepth

Complexity

qixuan-code commented 3 years ago

LC 104. maxium depth of a binary tree

python代码


class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:

        if root is None:
            return 0
        else:
            left_height = self.maxDepth(root.left)
            right_height = self.maxDepth(root.right)

            return 1+ max(left_height,right_height)
freesan44 commented 3 years ago

思路

用DFS来实现

代码

Python3 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: TreeNode) -> int:
        maxDepth = self.dfs(root, 0, 0)
        return maxDepth
    def dfs(self, node:TreeNode, cur:int, maxDepth:int) -> int:
        if node == None:
            # print(cur, maxDepth)
            return maxDepth
        cur += 1
        maxDepth = max(cur, maxDepth)
        leftMax = 0
        rightMax = 0
        if node.left:
            leftMax = self.dfs(node.left, cur, maxDepth)
        if node.right:
            rightMax = self.dfs(node.right, cur, maxDepth)
        # print(node.val,maxDepth,leftMax, rightMax)
        return max(leftMax, rightMax, maxDepth)

复杂度分析

令 n 为数组长度。