标签:题目 pre ini extra and 指针 root 使用 follow
仅供自己学习
题目:
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:
You may only use constant extra space.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
思路:
1. 前序遍历的方法最易想到,该方法需要处理的是,root->right的情况如何连接。考虑使用root->next->left来让root->right->next连接即可
代码:
1 class Solution { 2 public: 3 Node* connect(Node* root) { 4 if(root ==NULL) return NULL; 5 if(root->left) root->left->next = root->right; //如果有左孩子 6 if(root->right)root->right->next = root->next ? root->next->left : NULL; //如果有右孩子,并且ROOT->NEXT不为空 7 connect(root->left); 8 connect(root->right); 9 }
2. 还可用队列的方法。将一层的的结点全部加入进队列,且从左到右那么直接将前一个的next指向下一个结点即可。
代码:
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 queue<int> q; 23 q.push(root); 24 while(!q.empty()){ 25 int len = q.size(); 26 for(int i=0;i<len;++i){ 27 int t = q.front(); 28 q.pop(); 29 if(i<s-1){ //s-1是因为该层最右边的节点不需要连接 30 t->next=q.front(); 31 } 32 if(root->left) q.push(root->left); 33 if(root->right) q.push(root->right); 34 } 35 } 36 return root; 37 } 38 };
上面是两种对树操作的基本方法,还从网上学到了一种,就是双指针,一个指针固定在每层最左边的结点,cur指针通过next的连接而在该层移动。next连接的处理方法和递归方法一样,不同的点在于如何获取结点。
代码:
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==NULL) return NULL; 23 Node* start =root, *move=NULL; 24 while(start->left){ 25 move = start; 26 while(move){ 27 move->left->next = move->right; 28 if(move->next) move->right->next = move->next->left; 29 move=move->next; 30 } 31 start=start->left; 32 } 33 return root; 34 } 35 };
116. Populating Next Right Pointers in Each Node
标签:题目 pre ini extra and 指针 root 使用 follow
原文地址:https://www.cnblogs.com/Mrsdwang/p/14369905.html