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

LeetCode - Populating Next Right Pointers in Each Node

题目https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/

对每个节点递归。

 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         {14             return;15         }16         17         //任一节点的左儿子的next连右儿子18         if (root->left != NULL)19         {20             root->left->next = root->right;21         }22         23         //处理5连6情况24         //若2的next不为NULL,5连2的next的left25         if (root->right != NULL)26         {27             root->right->next = (root->next == NULL ? NULL : root->next->left);28         }29         30         //递归每个节点31         connect(root->left);32         connect(root->right);33     }34 };

 

LeetCode - Populating Next Right Pointers in Each Node