首页 > 代码库 > LeetCode--Populating Next Right Pointers in Each Node II
LeetCode--Populating Next Right Pointers in Each Node II
同上题:
但是这题需要考虑好对当前节点的left和right的next指针如何设置。
1 /** 2 * Definition for binary tree with next pointer. 3 * struct TreeLinkNode { 4 * int val; 5 * TreeLinkNode *left, *right, *next; 6 * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 * }; 8 */ 9 class Solution {10 public:11 void connect(TreeLinkNode *root) {12 if(root == NULL){13 return;14 }15 TreeLinkNode *leftNext = NULL;16 TreeLinkNode *rightNext = NULL;17 TreeLinkNode *node = NULL;18 if(root->left){19 leftNext = root->right;20 node = root->next;21 while(!leftNext && node){22 if(node->left){23 leftNext = node->left;24 break;25 }26 if(node->right){27 leftNext = node->right;28 break;29 }30 node = node->next;31 }32 root->left->next = leftNext;33 }34 if(root->right){35 rightNext = NULL;36 node = root->next;37 while(!rightNext && node){38 if(node->left){39 rightNext = node->left;40 break;41 }42 if(node->right){43 rightNext = node->right;44 break;45 }46 node = node->next;47 }48 root->right->next = rightNext;49 }50 connect(root->right);51 connect(root->left);52 }53 };
root->left和root->right顺序不能变。
LeetCode--Populating Next Right Pointers in Each Node II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。