题解 | #二叉树的下一个结点#

二叉树的下一个结点

https://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e

/*
struct TreeLinkNode {
    int val;
    struct TreeLinkNode *left;
    struct TreeLinkNode *right;
    struct TreeLinkNode *next;
    TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
        
    }
};
*/

/*
分三种情况:
1. 该节点有右子,直接找到右子树中的最左节点,并返回
2. 该节点无右子树
	1.该节点在其父节点的左树:直接返回其父节点
	2.在其父节点的右树,一直向父节点找。
*/
class Solution {
public:
    TreeLinkNode* GetNext(TreeLinkNode* pNode) {
        if(!pNode)
        {   
            return nullptr;
        }

        TreeLinkNode *pnext=nullptr;
        
        if(pNode->right)
        {   
            TreeLinkNode *pr=pNode->right;
            while(pr->left)
            {   
                pr=pr->left;
            }
            pnext=pr;
        }
        else if(pNode->next)
        {           
            TreeLinkNode *pcur=pNode;
            while(pcur->next&&pcur==pcur->next->right)
            {       
                pcur=pcur->next;
            }
            pnext=pcur->next;
        }
    return pnext;
    }
};

全部评论

相关推荐

星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务