题解 | #二叉树的下一个结点#【js实现】
二叉树的下一个结点
https://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e
1. 从当前节点pNode出发,找到根节点(根节点的next指向null)
2. 输入根节点,然后通过中序遍历函数获取到整棵树的中序遍历结果
3.遍历这棵树的中序遍历结果,找到与pNode值相同的节点,进而找到pNode值相同的下一个节点
// function TreeLinkNode(x){
// this.val = x;
// this.left = null;
// this.right = null;
// this.next = null;
// }
let mArr = []
function GetNext(pNode)
{
// 根据next指针寻找树的根节点
let root = pNode
while(root.next !== null) {
root = root.next
}
// 对树进行中序遍历
InOrders(root)
// let idx = mArr.indexOf(pNode)
// return mArr[idx + 1]
for(let i = 0; i < mArr.length-1; i++) {
if(pNode === mArr[i]) {
return mArr[i+1]
}
}
}
// 中序遍历
function InOrders(root) {
if(root !== null) {
InOrders(root.left)
mArr.push(root)
InOrders(root.right)
}
}
module.exports = {
GetNext : GetNext
};
