需求:
给定一个二叉树其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的next指针。下图为一棵有9个节点的二叉树。树中从父节点指向子节点的指针用实线表示,从子节点指向父节点的用虚线表示
输入:{8,6,10,5,7,9,11},8
返回:9
解析:这个组装传入的子树根节点,其实就是整颗树,中序遍历{5,6,7,8,9,10,11},根节点8的下一个节点就是9,应该返回{9,10,11},后台只打印子树的下一个节点,所以只会打印9,如下图,其实都有指向左右孩子的指针,还有指向父节点的指针,下图没有画出来
数据范围:节点数满足 1≤n≤50 ,节点上的值满足 1≤val≤100
要求:空间复杂度 O(1) \O(1) ,时间复杂度 O(n)\O(n)
输入描述:输入分为2段,第一段是整体的二叉树,第二段是给定二叉树节点的值,后台会将这2个参数组装为一个二叉树局部的子树传入到函数GetNext里面,用户得到的输入只有一个子树根节点
返回值描述:返回传入的子树根节点的下一个节点,后台会打印输出这个节点。
实现:
- 首先,完全理解中序遍历的特点和遍历顺序,先访问左子树,然后访问根节点,最后访问右子树。
- 想要得到该节点(以下用pNode表示)的下一个节点,就要知道pNode的位置,位置不同结果不同。
- 如果pNode不存在,则pNode的下一个节点为null。
- 如果pNode存在,则有以下情况:
① pNode 有 右 节 点 :
❤ pNode的右节点没有左子节点——pNode.right;
❤ pNode的右节点有左子节点——进行循环,直至pNode.right.left这颗子树上最左的节点。
if(pNode.right){
pNode = pNode.right;
while(pNode.left){
pNode = pNode.left;
}
return pNode;
}
② pNode 没 有 右 节 点 :
❤ 如果pNode的父节点(即pNode.next)不存在,则返回null;
❤ 如果pNode在父节点的左子节点上,则结果为pNode.next;
❤ 否则继续向上遍历其父节点的父节点,重复之前的判断,返回结果。
else{
if(pNode.next === null){
return null;
}
if(pNode.next.left === pNode){
return pNode.next;
}else{
while(pNode.next.left !== pNode){
pNode = pNode.next;
if(pNode.next === null){
return null
}
}
return pNode.next
}
}
/*function TreeLinkNode(x){
this.val = x;
this.left = null;
this.right = null;
this.next = null;
}*/
function GetNext(pNode)
{
// write code here
if(pNode === null){
return null;
}
// pNode是否有右结点
if(pNode.right){
pNode = pNode.right;
while(pNode.left){
pNode = pNode.left;
}
return pNode;
}else{
if(pNode.next === null){
return null;
}
if(pNode.next.left === pNode){
return pNode.next;
}else{
while(pNode.next.left !== pNode){
pNode = pNode.next;
if(pNode.next === null){
return null
}
}
return pNode.next
}
}
}
module.exports = {
GetNext : GetNext
};