Open azl397985856 opened 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;
}
}
思路
采用 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;
}
}
复杂度分析
/**
* 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))
}
Day 13 二叉树的最大深度
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
思路:
class Solution:
def maxDepth(self, root: TreeNode) -> int:
def dfs(root):
if not root :
return 0
left = dfs(root.left)
right = dfs(root.right)
depth = max(left,right)
return depth +1
return dfs(root)
复杂度分析:
时间复杂度:O(N),其中N为节点个数
空间复杂度: O(h),h为树的深度,最坏时候为N
递归,递归出口是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;
}
}
复杂度分析
使用深度优先对我理解比较友好,于是直接使用深度优先的方法递归左/右子树的深度。
const maxDepth = function(root) {
if(!root) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
};
时间复杂度: O(n), 需要遍历整个树的元素 空间复杂度: O(h), h为二叉树的高度,递归调用栈需要最大的空间就是它的高度。
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.
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;
}
};
O(n), we need to at least visit each node once
O(logn), the size of the recursion stack, worst case will be O(n), when the tree is a skewed tree
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);
}
}
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; } }
递归
var maxDepth = function (root) {
if (root === null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};
递归
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)
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)
考察二叉树的遍历。利用递归的思想,如果已知左子树深度,以及右子树深度,那么该节点的最大深度就是当中的最大值+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)
# 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)
深度优先,每次遍历到下一层计数器加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)
【思路】 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);
}
}
var maxDepth = function(root) { if(!root){ return 0 } return 1+Math.max(maxDepth(root.left),maxDepth(root.right)) };
复杂度:时间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 max(left, right) + 1;
}
};
时间:2021年9月22日13:02:21
思路:叶节点到根节点间的最大节点数(包括两端点),即深度。采用递归,为空返回0,否则返回左右子树(如果有的话)的最大深度。
/**
* 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;
}
/*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;
};
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;
};
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为二叉树的高度
var maxDepth = function(root) {
if (root === null) return 0
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
};
时间复杂度:O(n) 空间复杂度:O(h),h为二叉树的高度
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 为数组长度。
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)$ 树的深度
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
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;
}
}
}
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.
# 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
Time complexity: O(n). Since every node needs to be reached.
Space complexity: O(h).
递归法:以当前节点为根节点的树的最大高度等于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)
时间:O(N),N为节点个数
空间:O(N),N为节点个数
迭代法:层序遍历,每遍历到新的一层就把返回值加一
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)
时间:O(N),N为节点个数
空间:O(N),N为节点个数
/**
* @param {TreeNode} root
* @return {number}
*/
const maxDepth = function(root) {
if (!root) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};
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))
class Solution { public: int maxDepth(TreeNode* root) { if (root == nullptr) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } };
通过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
复杂度分析
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;
}
};
递归:
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 为二叉树节点数。
因为要求最大深度,跟层序遍历的逻辑是一样的。
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 为二叉树节点数。
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
“ class Solution: def maxDepth(self, root): if not root: return 0 else: return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) ”
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)
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; } };
* root为空时返回0,最终树的高度为左子树和右子树高度的最大值加1
/**
* 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;
}
};
/**
* 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;
}
}
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;
/**
* 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;
}
};
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [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;
}
};
时间复杂度:O(n),因为要遍历所有节点,层序遍历时间复杂度也是O(n);
空间复杂度:O(height),递归调用栈,栈使用的空间即为二叉树的高度、层序遍历为O(n),存放所有的节点数;
思路
代码
深度优先:
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;
}
复杂度
深度优先:
广度优先:
# 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
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
return 1+max(self.maxDepth(root.left), self.maxDepth(root.right))
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
时间复杂度 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));
}
};
树的最大深度 = 左子树最大深度与右子树最大深度最大深度 + 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)
104. 二叉树的最大深度
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
前置知识
题目描述
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例: 给定二叉树 [3,9,20,null,null,15,7],
/ \ 9 20 / \ 15 7 返回它的最大深度 3 。