Description

Given a binary tree

struct Node {
int val;
Node *left;
Node *right;
Node *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.

[leetcode] 117. Populating Next Right Pointers in Each Node II_空间复杂度

Input:

{"$id":"1","left":{"$id":"2","left":
{"$id":"3","left":null,"next":null,"right":null,"val":4},
"next":null,"right":
{"$id":"4","left":null,"next":null,"right":null,"val":5},
"val":2},
"next":null,"right":{"$id":"5","left":null,"next":null,"right":
{"$id":"6","left":null,"next":null,"right":null,"val":7},
"val":3},"val":1}

Output:

{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,
"next":{"$id":"4","left":null,"next":
{"$id":"5","left":null,"next":null,"right":null,"val":7},
"right":null,"val":5},"right":null,"val":4},
"next":{"$id":"6","left":null,"next":null,
"right":{"$ref":"5"},"val":3},"right":
{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"6"},"val":1}

Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B.

Note:

  • You may only use constant extra space.
  • Recursive approach is fine, implicit stack space does not count as extra space for this problem.

分析

题目的意思是:给一棵普通二叉树,对于每个节点,将next指针指向节点右边的节点,如果没有右边的节点,则置空。

  • 用了dummy指针,空间复杂度为O(1),dummy的引用给了pre,当pre第一次赋值的时候,相当于给dummy赋值了,dummy.next永远是一层的第一个节点。过程很巧妙。

代码

/**
* 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) {
while(root){
TreeLinkNode dummy(-1),*pre;
pre=&dummy;
for(auto p=root;p;p=p->next){
if(p->left){
pre->next=p->left;
pre=pre->next;
}
if(p->right){
pre->next=p->right;
pre=pre->next;
}
}
root=dummy.next;
}
}
};

参考文献

​[编程题]populating-next-right-pointers-in-each-node-ii​