Populating Next Right Pointers in Each Node II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012201343/article/details/49948101
  1. 问题

    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
    
  2. 解答
    class Solution {
    public:
        void connect(TreeLinkNode *root) 
        {
            queue<TreeLinkNode *> qu;
            if(!root) return ;
            qu.push(root);
            
            root->next=NULL;
            while(!qu.empty())
            {
                int len=qu.size();
                for(int i=0;i<len;i++)
                {
                    TreeLinkNode *temp=qu.front();
                    qu.pop();
                    if(i==len-1) 
                        temp->next=NULL;
                    else
                        temp->next=qu.front();
                    
                    if(temp->left)
                    {
                        qu.push(temp->left);
                    }
                    if(temp->right)
                    {
                        qu.push(temp->right);
                    }
                }
                //TreeLinkNode *temp1=qu.front();
               // temp1->next=NULL;
               // qu.pop();
                
            }
        }
    };


阅读更多

没有更多推荐了,返回首页