码迷,mamicode.com
首页 > 其他好文 > 详细

Populating Next Right Pointers in Each Node--LeetCode

时间:2015-04-11 00:07:02      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

题目:

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

标签:c++   leetcode   算法   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!