剑指offer8--二叉树的下一个结点——java/C++实现

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

思路:

失败:

刚开始想着先看根,再看叶子结点,再看中间。这样就没有结合题目,很麻烦了。

正确:

中序,有没有右子树,有的话,必须找右子树的最左边的节点

如果有根节点,那么得分是左子节点(直接返回父节点)

右子节点--------一直找父节点,如果父节点是右子节点,继续找,如果是左子节点,就返回这个节点的父节点~~~

如果过程中找到了根节点,那么就直接返回null。

 

/*
struct TreeLinkNode {
    int val;
    struct TreeLinkNode *left;
    struct TreeLinkNode *right;
    struct TreeLinkNode *next;
    TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
        
    }
};
*/
class Solution {
public:
    TreeLinkNode* GetNext(TreeLinkNode* pNode)
    {
        if(pNode==NULL)
            return NULL;
        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 if(pNode->next->right==pNode){//右叶子
                TreeLinkNode* tmp=pNode;
                while(tmp->next->right==tmp)
                {
                    tmp=tmp->next;
                    if(tmp->next==NULL||tmp==NULL){
                        return NULL; 
                    }
                }
                return tmp->next;
            }
        }
        return NULL;
    }
};
/*
public class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

    TreeLinkNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        if(pNode == null){
            return null;
        }
        if(pNode.right!=null){
            pNode = pNode.right;
            while(pNode.left!=null){
                pNode = pNode.left;
            }
            return pNode;
        }else{
            if(pNode.next ==null){
                return null;
            }
            if(pNode.next!=null){
                if(pNode.equals(pNode.next.left)){
                    return pNode.next;
                }else{
                    while(pNode.equals(pNode.next.right)){
                        pNode = pNode.next;
                        if(pNode.next==null){
                            return null;
                        }
                    }
                    return pNode.next;
                }
            }
        }
        
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值