Populating Next Right Pointers in Each Node II

xiaoxiao2021-02-28  128

Populating Next Right Pointers in Each Node II

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 解析:

与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==NULL) return ; queue<TreeLinkNode *>que; que.push(root); while(!que.empty()) { int cnt=que.size(); TreeLinkNode *temp; for (int i=0; i<cnt-1; i++) { temp=que.front(); if (temp->left) que.push(temp->left); if (temp->right) que.push(temp->right); que.pop(); temp->next=que.front(); } temp=que.front(); if (temp->left) que.push(temp->left); if (temp->right) que.push(temp->right); temp->next=NULL; que.pop(); } return ; } };

转载请注明原文地址: https://www.6miu.com/read-39110.html

最新回复(0)