zoukankan      html  css  js  c++  java
  • 二叉树中序遍历下一个节点

    #include<stdio.h>
    #include<string.h>
    #include <pthread.h>
    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <stack>
    #include <stdlib.h>
    #include <sstream>
    using namespace std;
    
    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 {
        //分为两大类:1,有右子树的,那么下个节点就是右子树最左边啊的点
        //2.没有右子树的a)是父节点的左孩子,那么父节点就是下一个节点b)时父节点的右孩子,找他的父节点的父节点的父节点,。。。。
        //直到当前节点时其父节点的左孩子的位置如果没有,那他就是尾节点
    public:
        TreeLinkNode* GetNext(TreeLinkNode* pNode)
        {
            if(pNode==NULL)
                return NULL;
            if(pNode->right!=NULL){
                pNode=pNode->right;
                while(pNode->left!=NULL)
                    pNode=pNode->left;
                return pNode;
            }
            while(pNode->next!=NULL){
                TreeLinkNode * proot=pNode->next;
                if(proot->left==pNode)
                    return proot;
                pNode=pNode->next;
            }
            return NULL;
        }
    };
    
    int main()
    {
        TreeLinkNode*t1=new TreeLinkNode(8);
        TreeLinkNode*t2=new TreeLinkNode(6);
        TreeLinkNode*t3=new TreeLinkNode(10);
        TreeLinkNode*t4=new TreeLinkNode(5);
        TreeLinkNode*t5=new TreeLinkNode(7);
        TreeLinkNode*t6=new TreeLinkNode(9);
        TreeLinkNode*t7=new TreeLinkNode(11);
        t1->left=t2;
        t1->right=t3;
        t2->left = t4;
        t2->right = t5;
        t3->left = t6;
        t3->right = t7;
        t2->next = t1;
        t3->next = t1;
        t4->next = t2;
        t5->next = t2;
        t6->next = t3;
        t7->next = t3;
        Solution s;
        if(s.GetNext(t1)==NULL)
            cout<<"NO next point "<<endl;
        else
            cout<<"s.GetNext(t1): "<<s.GetNext(t1)->val<<endl;
        return 0;
    
    }
    
  • 相关阅读:
    qt install (1)
    learning rewind func
    learning strrchr func
    learning memchr func
    git lfs setpu(4)
    大端与小端
    git branch/meger step(3)
    git log/show/HEAD step(2)
    调用外部EXE文件
    获取计算机上的所有进程
  • 原文地址:https://www.cnblogs.com/bananaa/p/7541621.html
Copyright © 2011-2022 走看看