标签:space upload HERE root you rgba poi sig less
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
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
.
Follow up:
Example 1:
Input: root = [1,2,3,4,5,6,7] Output: [1,#,2,3,#,4,5,6,7,#] Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with ‘#‘ signifying the end of each level.
Constraints:
4096
.-1000 <= node.val <= 1000
题目难度:简单题
考察点:dfs,bfs
代码一:用bfs解决,建立一个队列即可。C++代码如下:
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 Node* left; 7 Node* right; 8 Node* next; 9 10 Node() : val(0), left(NULL), right(NULL), next(NULL) {} 11 12 Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} 13 14 Node(int _val, Node* _left, Node* _right, Node* _next) 15 : val(_val), left(_left), right(_right), next(_next) {} 16 }; 17 */ 18 19 class Solution { 20 public: 21 Node* connect(Node* root) { 22 if (root == nullptr) return root; 23 queue<Node*> q; 24 Node *f, *r; 25 q.push(root); 26 while (!q.empty()) { 27 int len = q.size(); 28 f = q.front(); 29 q.pop(); 30 if (f->left != nullptr) 31 q.push(f->left); 32 if (f->right != nullptr) 33 q.push(f->right); 34 for (int i = 1; i < len; ++i) { 35 r = q.front(); 36 q.pop(); 37 f->next = r; 38 f = r; 39 if (r->left != nullptr) { 40 q.push(r->left); 41 } 42 if (r->right != nullptr) { 43 q.push(r->right); 44 } 45 } 46 } 47 return root; 48 } 49 };
代码二:dfs,递归形式
1 class Solution { 2 public: 3 Node* connect(Node* root) { 4 if (root == nullptr) 5 return root; 6 if (root->left) { 7 root->left->next = root->right; 8 if (root->next != nullptr) { 9 root->right->next = root->next->left; 10 } 11 } 12 connect(root->left); 13 connect(root->right); 14 return root; 15 } 16 };
代码三:dfs,非递归形式(迭代)
class Solution { public: Node* connect(Node* root) { Node *prev, *cur; prev = root; //利用队列的那种思路,一行一行来 while (prev) { cur = prev; while (cur && cur->left) { cur->left->next = cur->right; if (cur->next != nullptr) { cur->right->next = cur->next->left; } cur = cur->next; } prev = prev->left; } return root; } };
leetcode 116. Populating Next Right Pointers in Each Node
标签:space upload HERE root you rgba poi sig less
原文地址:https://www.cnblogs.com/qinduanyinghua/p/13983163.html