JZ8 二叉树的下一个结点 C++ 详细注释

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

思路1:对树进行中序遍历,用数组保存遍历结果

    vector<TreeLinkNode *> in;	//保存中序遍历结果
    
    TreeLinkNode *GetRoot(TreeLinkNode *pNode) {
        while (pNode->next)	 pNode = pNode->next;
        return pNode;
    }
 
    void InOrder(TreeLinkNode *pNode) {
        if (pNode->left)	InOrder(pNode->left);
        in.push_back(pNode);
        if (pNode->right)	InOrder(pNode->right);
    }
 
    TreeLinkNode *GetNext(TreeLinkNode *pNode) {
        TreeLinkNode *pRoot = GetRoot(pNode);	// 找到树根
        InOrder(pRoot);							// 从树根开始中序遍历
        for (int i = 0; i < in.size(); ++i) {
            if (in[i]->val == pNode->val && i+1<in.size()){
                return in[i+1];
            }
        }
        return nullptr;
    }

思路2:分析中序遍历的特点

TreeLinkNode *GetLeftMost(TreeLinkNode *pNode) {
    while (pNode->left)	pNode = pNode->left;
    return pNode;
}

TreeLinkNode *GetNext(TreeLinkNode *pNode) {
    if (pNode->right) {
        // 当前结点存在右子树,返回右子树的最左结点
        return GetLeftMost(pNode->right);
    } else {
        // 当前结点无右子树时,判断结点是父结点的左子树还是右子树
        while(pNode->next != nullptr){
            if(pNode->next->left == pNode)
                return pNode->next;     // 若是左子树,返回父节点
            pNode = pNode->next;        // 若是右子树,继续判断其父节点
        }
        return nullptr;	// 当pNode是中序遍历的最后一个结点才会走到这里
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值