二叉树中加横向指针 以及多叉树转为二叉树

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(root==NULL){
            return ;
        }
        queue<TreeLinkNode *>  que;
        vector<TreeLinkNode *> ivec;
        vector<vector<TreeLinkNode *> > iivec;
        
        que.push(root);
        TreeLinkNode *last=root,*nlast=NULL;
        
        while(!que.empty()){
            TreeLinkNode *temp=que.front();
            que.pop();
            ivec.push_back(temp);
            
            if(temp->left){
                que.push(temp->left);
                nlast=temp->left;
            }
            if(temp->right){
                que.push(temp->right);
                nlast=temp->right;
            }
            if(temp==last){
                iivec.push_back(ivec);
                ivec.clear();
                last=nlast;
            }
        }
        
        for(int i=0;i<iivec.size();++i){
            for(int j=1;j<iivec[i].size();++j){
                iivec[i][j-1]->next=iivec[i][j];
            }
        }
        
    }
    
    
};

2  多叉树转二叉树的方法

1、输入一颗多叉树

2、找到根节点,把它除最左边的儿子以外的所有儿子的关系断掉

3 从左儿子开始,把同层的兄弟依次连接起来

4 然后对根节点的儿子依次递归进行次操作,最后转出来的二叉树就是这个样子

猜你喜欢

转载自blog.csdn.net/u010325193/article/details/86209073
今日推荐