Open azl397985856 opened 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)
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 为数组长度。
可以用递归处理, 也可以使用层次遍历将每层的值放进二维数组中, 最后看二维数组的size是多少。
递归做的话,如果root == NULL, 直接返回0。否则看左子树的最大深度是多少,右子树的最大深度是多少,最后取较大者+1,+1是因为root的深度是1。
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
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();
}
};
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)
递归,终止条件是为叶子结点,返回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;
}
};
递归
class Solution:
def maxDepth(self, root):
if not root:
return 0
else:
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.right), maxDepth(root.left)) + 1;
}
}
经典递归
1,递归法
class Solution {
public:
// 递归法
int maxDepth(TreeNode* root) {
if(root){
return 1 + max(maxDepth(root -> left), maxDepth(root -> right));
}
else{
return 0;
}
}
};
递归,出口为空结点,每层高度+1。
# 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) 需比较的常数的数量级与二叉树的高度成正比
深度遍历
# 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)
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;
}
}
递归左右节点,返回最大值
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)
递归: 以当前节点为根目录的树的最大深度为该问题的子问题 构建子问题和母问题的关系等式 确定终止条件:若结点自身为空,则返回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
https://leetcode.com/problems/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 left = maxDepth(root.left);
int right = maxDepth(root.right);
return 1 + Math.max(left, right);
}
}
Complexity
深度递归 广度遍历
/**
* 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
};
python
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
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;
}
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
};
# 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))
递归
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
}
}
}
复杂度分析
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)
DFS: return 1 + max(left, right)
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)
广度优先搜索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)
深度优先搜索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),递归函数需要的空间取决于树的高度
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)
递归,最大深度为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
};
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);
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)))
思路:
复杂度分析:
代码(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;
}
};
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)
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
DFS while practice to use recursion
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
If root == null
, then the depth is 0
, else depth = max{left, right} + 1
.
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) = O(n)
, stack space.
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.
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;
}
}
Time: O(n)
.
Space: O(n)
, heap space.
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.
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;
}
}
Time: O(n)
Space: O(h) = O(n)
, heap space
思路:用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)
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)'
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;
}
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)
标准dfs 求深度
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
时间复杂度O(n)
空间复杂度O(h),h为树的高度
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;
}
}
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为树的高度
https://leetcode.com/problems/maximum-depth-of-binary-tree/
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)?
如果根节点为空,高度为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;
}
};
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;
}
};
递归,取左右中的最大值
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)
Language: Java
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
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)
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)
Recursive
fun maxDepth(root: TreeNode?): Int = root?.let { maxOf(maxDepth(it.left), maxDepth(it.right)) + 1 } ?: 0
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
O(N)
O(N)
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)
用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 为数组长度。
104. 二叉树的最大深度
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
前置知识
题目描述
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例: 给定二叉树 [3,9,20,null,null,15,7],
/ \ 9 20 / \ 15 7 返回它的最大深度 3 。