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

    欢迎fork and star:Nowcoder-Repository-github

    117. Populating Next Right Pointers in Each Node II

    题目

    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
    
    
    

    解析

    // Populating Next Right Pointers in Each Node
    class Solution_117 {
    public:
    	//运行时间:8ms
        //占用内存:892k
    	//使用层次遍历,每一层从左到右串接起来就行,每层最后一个元素next置NULL即可!
    	void connect(TreeLinkNode *root) {
    		if (!root)
    		{
    			return;
    		}
    		queue<TreeLinkNode*> que;
    		que.push(root);
    
    		while (!que.empty())
    		{
    			int size = que.size(); //每一层的大小
    
    			TreeLinkNode* cur, *pre=NULL;
    			while (size--)
    			{
    				cur= que.front();
    				que.pop();
    
    				if (pre)
    				{
    					pre->next = cur;		
    				}
    				pre = cur;
    				if (cur->left)
    				{
    					que.push(cur->left);
    				}
    				if (cur->right)
    				{
    					que.push(cur->right);
    				}
    			}
    			cur->next = NULL;
    
    		}
    	}
    
    	void connect1(TreeLinkNode *root) {
    		queue<TreeLinkNode*> q;
    		if (!root)
    			return;
    		q.push(root);
    
    		while (!q.empty()) {
    			int size = q.size();
    			for (int i = 0; i < size; i++) {
    				TreeLinkNode* node = q.front();
    				q.pop();
    				if (i == size - 1)
    					node->next = nullptr;
    				else
    					node->next = q.front();//当前节点已经出栈, q.front()为下一节点,避免记录上一次节点
    
    				if (node->left)
    					q.push(node->left);
    				if (node->right)
    					q.push(node->right);
    			}
    		}
    	}
    };
    

    117. Populating Next Right Pointers in Each Node II

  • 相关阅读:
    java_监控工具jvisualvm
    bzoj3667: Rabin-Miller算法
    bzoj3677: [Apio2014]连珠线
    4070: [Apio2015]雅加达的摩天楼
    4069: [Apio2015]巴厘岛的雕塑
    4071: [Apio2015]巴邻旁之桥
    bzoj2653: middle
    1500: [NOI2005]维修数列
    bzoj4262: Sum
    bzoj4540: [Hnoi2016]序列
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8214969.html
Copyright © 2011-2022 走看看