zoukankan      html  css  js  c++  java
  • 二叉树的下一个节点

    题目描述

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

    解题思路:

    情况一、所给的节点的右子树不是空,则顺着找最小的

    情况二、所给的节点右子树是空,且是左儿子则返回父节点

    情况三、所给的节点右子树是空,且是右儿子且父亲是祖父的左儿子,则返回祖父节点

    class Solution {
    public:
        TreeLinkNode* getRoot(TreeLinkNode* pNode){
            TreeLinkNode* root = NULL;
            while(pNode != NULL){
                root = pNode;
                pNode = pNode->next;
            }
            return root;
        }
        TreeLinkNode* _getNext(TreeLinkNode* root, TreeLinkNode *pNode){
            if(root == NULL) return NULL;
    //        cout<<"rval="<<root->val<<endl;
            if(root == pNode){
                TreeLinkNode * res = NULL;
                if(root->right != NULL){
                    //当前节点的右子树不是空则顺着找最左的节点
                    res = root->right;
                    while(res != NULL){
                        if(res->left != NULL){
                            res = res->left;
                        }else{
                            break;
                        }
                    }
                }else{
                    if(root->next != NULL){
                        if(root->next->left == root){
                            //如果当前节点的右子树为空且当前节点是左子树
                            return root->next;
                        }else if(root->next->right == root && root->next == root->next->next->left){
                            //如果当前节点的右子树为空,当前节点是右子树且父节点是祖父的左子树
                            return root->next->next;
                        }
                    }
                }
    //            cout<<"xxx"<<endl;
                return res;
            }else{
    
                TreeLinkNode* lRes = NULL;
                if(root->left != NULL){
                    lRes = _getNext(root->left, pNode);
                }
                TreeLinkNode * rRes = NULL;
                if(root->right != NULL){
                    rRes = _getNext(root->right, pNode);
                }
                if(lRes != NULL){
                    return lRes;
                }else if(rRes != NULL){
                    return rRes;
                }else{
                    return NULL;
                }
            }
        }
        TreeLinkNode* GetNext(TreeLinkNode* pNode)
        {
            TreeLinkNode *root = getRoot(pNode);
            return _getNext(root, pNode);
        }
    };
    

      

  • 相关阅读:
    zabbix 监控机器监听的端口 + 触发器 表达式理解
    php关于文件上传的两个配置项说明
    linux cron计划任务防止多个任务同时运行
    php注册自动加载函数
    linux 下查看机器是cpu是几核的
    laravel容器类make方法解释
    laravel php门面模式
    js获取当前页面的url地址
    php编码规范
    laravel console handle 传参方法
  • 原文地址:https://www.cnblogs.com/chengsheng/p/10698316.html
Copyright © 2011-2022 走看看