LeetCode 117. Populating Next Right Pointers in Each Node II

来源:互联网 发布:上海淘宝运营培训班 编辑:程序博客网 时间:2024/06/05 02:56

和LeetCode 102. Binary Tree Level Order Traversal差不多个意思。
用q维护同一高度的节点,先进先出进行操作即可。


代码和LeetCode 116. Populating Next Right Pointers in Each Node相同:

class Solution {public:    void connect(TreeLinkNode *root)     {    queue<TreeLinkNode*> nodes;    queue<TreeLinkNode*> children;    nodes.push(root);    nodes.push(NULL);    while ( nodes.front() != NULL )    {    auto cur = nodes.front();    nodes.pop();    cur->next = nodes.front();    if (cur->left != NULL)   {   children.push( cur->left );   }   if (cur->right != NULL)    {       children.push( cur->right );   }   if (nodes.front() == NULL)   {    nodes = children;    nodes.push(NULL);    while (children.empty() == false)    {    children.pop();    }    }    }    }};


0 0
原创粉丝点击