标签:node right TreeNode cur Offer 55 int 二叉树 root
剑指 Offer 55 - I. 二叉树的深度
比较常见的递归,但是可能在面试过程中会要求要写非递归写法。
递归写法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
return deep(root);
}
private int deep(TreeNode node) {
if(node == null) return 0;
return 1 + Math.max(deep(node.left), deep(node.right));
}
}
时间复杂度\(O(logn)\),空间复杂度\(O(1)\),其中n为节点数量,最多遍历\(logn\)层。
非递归写法:
①.层次遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
int ans = 0;
if(root == null) {
return ans;
}
Queue<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while(!q.isEmpty()) {
var size = q.size();
for(int i = 0; i < size; i++) {
var node = q.poll();
if(node.left != null) {
q.offer(node.left);
}
if(node.right != null) {
q.offer(node.right);
}
}
ans++;
}
return ans;
}
}
②.非递归dfs
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
// 这里不仅要存节点,还需要存节点的高度
Stack<Pair<TreeNode, Integer>> st = new Stack<>();
int depth = 0, max = 0;
TreeNode cur = root;
while(!st.isEmpty() || cur != null) {
while(cur != null) {
st.push(new Pair<>(cur, ++depth));
cur = cur.left;
}
var top = st.pop();
cur = top.getKey();
depth = top.getValue();
max = Math.max(max, depth);
cur = cur.right;
}
return max;
}
}
标签:node,right,TreeNode,cur,Offer,55,int,二叉树,root 来源: https://www.cnblogs.com/nullpointer-c/p/15859212.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。