Populating Next Right Pointers in Each Node II - LeetCode 117

题目描述:
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
Hide Tags Tree Depth-first Search

分析:此题的思路和Populating Next Right Pointers in Each Node(http://blog.csdn.net/bu_min/article/details/45921295)是一样的,只是处理的时候,要跳过二叉树的空节点。next指针要指向其右边第一个非空节点。
只需在上一题的基础上跳过二叉树中的空节点,处理每一层的时候,注意判断其左右孩子是否为空,只将非空节点放入向量和队列中。

以下是C++实现代码:

/*/44ms*/
/**
 * 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;
        TreeLinkNode *cur = root;
        queue<TreeLinkNode* > q;		
	    root->next = NULL; //修改root的next指针
        if(cur != NULL)
	    {
	        q.push(cur);
	        while(!q.empty()) //此处判断是否最后一层处理完
	        {
		        int len = 0;
		        vector<TreeLinkNode*> vec; //存放即将要处理得层的每个节点的左右节点
		        while(!q.empty()) //此处判断某一层是否处理完
		        {
		            TreeLinkNode *cur = q.front();
		            q.pop();
		            if(cur->left != NULL)  //依次将非空的左右孩子放入vec中
		            {
		                vec.push_back(cur->left);  
		                len++;
		            }
		            if(cur->right != NULL)
		            {
		                vec.push_back(cur->right);
		                len++;
		            }
	    	    }
	    	    if(len > 0) 当有非空左右孩子时,才修改next指针,将其指向右边的第一个非空节点
	    	    {
		            for(int i = 0; i < len-1; i++) 
		            {
			            q.push(vec[i]);
			            vec[i]->next = vec[i+1];
		            }
		
		            q.push(vec[len-1]);
		            vec[len - 1]->next = NULL;
	    	    }
	        }
        }
        return;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值