首页 > 代码库 > LeetCode--Populating Next Right Pointers in Each Node

LeetCode--Populating Next Right Pointers in Each Node

由于题目意思是满二叉树:

所以,对当前节点,设置它的左右子节点的next指针即可

root->left->next = root->right

root->right->next = root->next?root->next->left:NULL

 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         if(root->left != NULL){15             root->left->next = root->right;16         }17         if(root->right != NULL){18             root->right->next = root->next?root->next->left:NULL;19         }20         connect(root->left);21         connect(root->right);22     }23 };

 

LeetCode--Populating Next Right Pointers in Each Node