zoukankan      html  css  js  c++  java
  • 剑指offer58 二叉树的下一个结点

    自己写的

    class Solution {
    public:
        TreeLinkNode* GetNext(TreeLinkNode* pNode)
        {
            if(pNode == NULL)
                return NULL;
            if(pNode->right != NULL){
                TreeLinkNode* origin = pNode->right;
                while(origin->left != NULL)
                    origin = origin->left;
                return origin;
            }
            else{
                TreeLinkNode* father = pNode->next;
                if(father != NULL){
                    if(father->left == pNode)
                        return father;
                    while(father != NULL && father->right == pNode){
                        pNode = father;
                        father = pNode->next;
                    }
                }
                return father;
            }
        }
    };
    father != NULL && father->right == pNode这个前后顺序不能换,换了就会报以下错误:
                段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起


    书上的写法:
    /*
    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 != NULL){
                TreeLinkNode* next = pNode->right;
                while(next->left != NULL){
                    next = next->left;
                }
                return next;
            }
            else{
                TreeLinkNode* nextone = pNode;
                TreeLinkNode* father = pNode->next;
                while(father != NULL && father->left != nextone){
                    nextone = father;
                    father = nextone->next;
                }
                return father;
            }
        }
    };
    
    

    father != NULL一定要注意,这种情况一个是让father->left能不报错,还有一个就是解决了一个bad case,就是这个结点就是最后一个结点就返回NULL,或者说万一父结点全是右子树的




  • 相关阅读:
    undefined symbol 问题解决记录
    2021年中国数字人民币发展研究报告
    如何画出优秀的架构图
    用SIKT模型,让用户画像效果倍增
    全面总结图表设计
    如何用一周了解一个行业
    未来社区解决方案
    增长4大阶段,实现营销倍增的核心法则
    裂变营销的3个层次,让你实现指数增长
    运营的3个层面,让你轻松获得忠实用户
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/7232628.html
Copyright © 2011-2022 走看看