标签:style blog http io ar color sp for on
题目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的left 25 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
标签:style blog http io ar color sp for on
原文地址:http://www.cnblogs.com/bournet/p/4107744.html