首页 > 其他 > 详细

Populating Next Right Pointers in Each Node--LeetCode

时间:2015-04-11 00:05:22      阅读:169      评论:0      收藏:0      [点我收藏+]

题目:

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

         1
       /        2    3
     / \  /     4  5  6  7

After calling your function, the tree should look like:

         1 -> NULL
       /        2 -> 3 -> NULL
     / \  /     4->5->6->7 -> NULL
思路:只是把每个节点都添加了一个next节点,对于一棵树,把next节点都进行赋值,而且是一个完全二叉树,可以使用层次遍历,为每一层都进行改造。

void Connect(BinTree* root)
{
     if(root == NULL)
         return ;
     deque<BinTree*> de;
     de.push_back(root);
     int i,level=1;
     BinTree* cur,*pre; 
     while(!de.empty())
     {
         cur = NULL;
         pre = NULL;
         for(i=0;i<level&&!de.empty();i++)
         {
             if(pre == NULL)
             {
               pre = de.front();
               if(pre->left != NULL)
                de.push_back(pre->left);
               if(pre->right !=NULL)
                de.push_back(pre->right);
               de.pop_front();
               cout<<pre->value<<endl;
               continue;    
             }      
             if(cur == NULL)
             {
               cur = de.front();
               if(cur->left != NULL)
                de.push_back(cur->left);
               if(cur->right !=NULL)
                de.push_back(cur->right);
               de.pop_front();
               cout<<cur->value<<endl;
               continue; 
             }
             pre->next =cur;
             pre = cur;
             cur = de.front();
             de.pop_front();
             if(cur->left != NULL)
               de.push_back(cur->left);
             if(cur->right != NULL)
               de.push_back(cur->right); 
              cout<<cur->value<<endl;       
         }
         
         if(cur == NULL)
           pre->next == NULL;
         else
         {
           pre->next = cur;
           cur->next == NULL;  
         }
         level *=2;            
     }
}





Populating Next Right Pointers in Each Node--LeetCode

原文:http://blog.csdn.net/yusiguyuan/article/details/44985757

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!