目录
每日一句
再长的路,一步步也能走完,再短的路,不迈开双脚也无法到达
作者简介
🏡个人主页:XiaoChen_Android
📚学习专栏:力扣专栏
🕒发布日期:2022/8/31
『LeetCode|每日一题』后继者
1.每日一题
2.解题思路(递归)
2.1 思路分析
首先整体分析此题,简单来说其实就是把二叉树节点拿出来排序后找到下一个比它大的那个节点,那么此题其实就是找出比p节点值大的后继第一个节点,所以利用中序遍历可以很好的解决此题
S1:如果根节点为空,说明没有后继节点,那么直接返回空节点即可;
S2:如果根节点不为空,先看左节点,如果左节点能够找到,则返回该节点,然后继续递归调用函数;
S3:如果左节点没找到,再看根节点,此时根节点就是上一轮找到的最后的左节点,如果该点的值大于要找的那个后继点的节点的值(p),那么返回该节点;
S4:如果根节点也没找到,那么最后就找右节点,递归遍历所有右节点,如果中间找到了,那么返回该节点,如果也没有找到,说明后继点为null
2.2 完整代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if(root == null) return root;
TreeNode res = inorderSuccessor(root.left , p);
if(res != null) return res;
if(root.val > p.val) return root;
return inorderSuccessor(root.right , p);
}
}
2.3 运行结果
3.解题思路(非递归)
3.1 思路分析
该方法还是选用了中序遍历,由于题目要求是找到后继点,那么只需要当前节点和上一个点即可,如果上一个节点是p,那么返回当前节点即可
S1:定义一个双端队列用来存二叉树的节点,首先把二叉树的左节点都存进去;
S2:然后取出第一个的左节点,判断pre节点也就是上一个节点如果等于p,那么说明current节点就是后继点;(双端队列用作堆栈时,从队首开始推入数据,取出来也是从队首开始)
S3:如果pre节点不等于p,那么此时把取出来的左节点给pre,那么current就应该等于它的右节点了;
S4:如果右节点为空的话,那么就返回空,说明没有后继点,只有当pre节点等于p时,说明当前节点current就为后继点
3.2 核心代码
while(queue.isEmpty() == false || current != null){
while(current != null){
queue.push(current);
current = current.left;
}
current = queue.pop();
if(pre == p){
return current;
}
pre = current;
current = current.right;
}
3.3 完整代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
Deque<TreeNode> queue = new ArrayDeque<TreeNode>();
TreeNode pre = null;
TreeNode current = root;
while(queue.isEmpty() == false || current != null){
while(current != null){
queue.push(current);
current = current.left;
}
current = queue.pop();
if(pre == p){
return current;
}
pre = current;
current = current.right;
}
return null;
}
}
3.4 运行情况
🍁 类似题目推荐:
如果文章对各位大佬有帮助就支持一下噢,新手尝试,不好的地方请各位大佬多多指教!