116. Populating Next Right Pointers in Each Node

来源:互联网 发布:ubuntu 网卡重启不生效 编辑:程序博客网 时间:2024/06/03 18:56

题目

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
分析

层次遍历完全二叉树,用两个deque保存节点,当前队列为flag所指向队列,队首元素出队后根据是否有左子节点判断是否为最下层,如果不是则在1-flag中保存其左右子节点,然后根据flag队列是否为空决定当前元素的next指向,如果当前队列为空的转换flag值指向下一层的队列,由于最后一层不会向下一层队列压入任何节点,所以while循环能够在全部遍历后退出。

/** * Definition for binary tree with next pointer. * struct TreeLinkNode { *  int val; *  TreeLinkNode *left, *right, *next; *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */class Solution {public:    void connect(TreeLinkNode *root) {        if(root==NULL)            return ;        vector< deque<TreeLinkNode*> > v(2);        int flag=0;        v[0].push_back(root);        while(!v[flag].empty()){            TreeLinkNode* t=v[flag].front();            v[flag].pop_front();            if(t->left!=NULL){                v[1-flag].push_back(t->left);                v[1-flag].push_back(t->right);                       }            if(!v[flag].empty())                t->next=v[flag].front();            else                flag=1-flag;        }    }};