zoukankan      html  css  js  c++  java
  • Leetcode 树 Populating Next Right Pointers in Each Node II

    本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


    Populating Next Right Pointers in Each Node II

     Total Accepted: 9695 Total Submissions: 32965

    Follow up for problem "Populating Next Right Pointers in Each Node".

    What if the given tree could be any binary tree? Would your previous solution still work?

    Note:

    • You may only use constant extra space.

    For example,
    Given the following binary tree,

             1
           /  
          2    3
         /     
        4   5    7
    

    After calling your function, the tree should look like:

             1 -> NULL
           /  
          2 -> 3 -> NULL
         /     
        4-> 5 -> 7 -> NULL



    题意:给定一棵随意二叉树(不一定是perfect binary tree),将它每个节点的next指针都指向该节点右边的节点

    思路:bfs
    这里不能用dfs了,仅仅能用bfs
    bfs遍历将同一层的节点存放在同一个数组里,
    然后在遍历每一个数组,将前面的节点和后面的节点connect起来,
    最后一个节点和NULL connect起来
    须要定义一个新的struct结构,保存指向每一个节点的指针和该节点所在的层

    复杂度:时间O(n), 空间O( n)
    相关题目:

    Populating Next Right Pointers in Each Node



    /**
     * 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:
    
    
    
    
        
        struct TreeLinkNodeWithLevel
        {
        	TreeLinkNode *p;
        	int level;
        	TreeLinkNodeWithLevel(TreeLinkNode *pp, int l):p(pp), level(l){}
        };
        
        
        void connect(TreeLinkNode *root) {
        	vector<vector<TreeLinkNode *> > nodes;
        	queue<TreeLinkNodeWithLevel> q;
        	q.push(TreeLinkNodeWithLevel(root, 0));
        	while (!q.empty())
        	{
        		TreeLinkNodeWithLevel cur = q.front(); q.pop();
        		if(!cur.p) continue;
        		if(cur.level >= nodes.size()){
        			vector<TreeLinkNode *> temp;
        			temp.push_back(cur.p);
        			nodes.push_back(temp);
        		}else{
        			nodes[cur.level].push_back(cur.p);
        		}
        		TreeLinkNodeWithLevel left(cur.p->left, cur.level + 1);
        		TreeLinkNodeWithLevel right(cur.p->right, cur.level + 1);
        		q.push(left);
        		q.push(right);
        	}
        	for(int i = 0; i < nodes.size(); i++){
        		for(int j = 0; j < nodes[i].size() - 1; j++){
        			nodes[i][j]->next = nodes[i][j + 1];
        		}
        		nodes[i][nodes[i].size() - 1]->next = NULL;
        	}
        }
    };


  • 相关阅读:
    异构数据库同步工具调研
    ubuntu16.04 Golang语言开发环境搭建
    串口USB单一映射及重命名
    linux arm 交叉编译ACE(ubuntu16.04)
    ubuntu16.04 下Mongo数据库搭建
    ubuntu 增加一个用户 并赋予权限
    go 通过http发送图片file内容
    git 简单命令总结
    gitlab ssh_key
    ubuntu16.04 程序开机自启动设置及启动优化
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/3761808.html
Copyright © 2011-2022 走看看