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,或者说万一父结点全是右子树的




  • 相关阅读:
    Java 面向对象(十二)类的成员 之 代码块
    Java 关键字:static
    Java 常用类(二):包装类(Wrapper)
    Java 之 clone 方法(对象拷贝)
    SQL分组聚合查询
    Rabbitmq消息持久化
    idea 插件
    TCP粘包,拆包及解决方法
    redis内存淘汰策略及如何配置
    MySQL存储过程/存储过程与自定义函数的区别
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/7232628.html
Copyright © 2011-2022 走看看