Populating Next Right Pointers in Each Node II
  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();
                
            }
        }
    };


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012201343/article/details/49948101
文章标签: 二叉树
个人分类: LeetCode
想对作者说点什么? 我来说一句

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

不良信息举报

Populating Next Right Pointers in Each Node II

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭