LeetCode 117. Populating Next Right Pointers in Each Node II

来源:互联网 发布:淘宝双十一满减规则 编辑:程序博客网 时间:2024/05/18 00:51

描述

把每层的节点连接起来,要求O(1)的空间

解决

不会,看了这个算法写的,利用一个辅助节点记录每一层的开始节点


/** * 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)            return ;        while (root)        {            TreeLinkNode temp(-1);            TreeLinkNode *zz = &temp;            while (root)            {                if (root -> left)                {                    zz -> next = root -> left;                    zz = zz -> next;                }                if (root -> right)                {                    zz -> next = root -> right;                    zz = zz -> next;                }                root = root -> next;            }            root = temp.next;        }        return ;    }};
0 0
原创粉丝点击