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




  • 相关阅读:
    Partition算法及Partition算法用于快速排序
    任意增减文件上传栏
    java版的下雪,大家圣诞快乐
    Java聊天室[长轮询]
    java汉字转拼音以及得到首字母通用方法
    RTree算法Java实现 JSI RTree Library的调用实例 标签:jsi-rtree-library
    JAVA压缩 解压缩zip 并解决linux下中文乱码
    Java 线程转储
    用 Java 抓取优酷、土豆等视频
    Java Web 项目打包脚本
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/7232628.html
Copyright © 2011-2022 走看看