剑指offer JavaScript版 (57)

二叉树的下一个节点

题目描述

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

  • 该节点有右子树,则其下一个节点为其右子树的最左子节点;
  • 该节点没有右子树
    • 该节点为其父节点的左子节点,则其下一节点为其父节点
    • 该节点为其父节点的右子节点,则其下一节点为其父节点的左子节点
function GetNext(pNode)
{
    // write code here
    if(pNode==null){
        return null;
    }
    if(pNode.right!=null){
        pNode=pNode.right;
        while(pNode.left!=null){
            pNode=pNode.left;
        }
        return pNode;
    }
    while(pNode.next!=null){
        if(pNode===pNode.next.left){
            return pNode.next
        }
        pNode=pNode.next;
    }
    return null;
}
发布了93 篇原创文章 · 获赞 3 · 访问量 2482

猜你喜欢

转载自blog.csdn.net/Damp_XUN/article/details/99578035
今日推荐