关闭

Populating Next Right Pointers in Each Node II

标签: 二叉树
113人阅读 评论(0) 收藏 举报
分类:
  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();
                
            }
        }
    };


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:10636次
    • 积分:520
    • 等级:
    • 排名:千里之外
    • 原创:42篇
    • 转载:7篇
    • 译文:0篇
    • 评论:0条