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




  • 相关阅读:
    量化投资_期货日内交易几个问题的考证
    量化投资_上一个交易时间段对今日收盘价涨跌的影响
    RunJS
    sublime3快捷 输入html
    NLP学习资源
    Invert Binary Tree
    定时任务 Crontab命令 详解
    根据职位名,自动生成jd
    使用python + tornado 做项目demo演示模板
    Awk 实例
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/7232628.html
Copyright © 2011-2022 走看看