标签:
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { if(root == NULL || (root->left==NULL && root->right==NULL) ) return; TreeLinkNode *tmp = root; TreeLinkNode *tmp2 = NULL; TreeLinkNode *next = NULL; while(root) { tmp2 = NULL; if(root->left && root->right) { root->left->next = root->right; tmp2 = root->right; } else if(root->left == NULL) { tmp2 = root->right; tmp2->next = NULL; } else if(root->right == NULL) { tmp2 = root->left; tmp2->next = NULL; } TreeLinkNode *tmp3 = root->next; while(tmp3) { if(tmp3->left || tmp3->right) { tmp2->next = ((tmp3->left != NULL) ? tmp3->left:tmp3->right); next = tmp3; break; } tmp3 = tmp3->next; } root = tmp3; } if(tmp->left) connect(tmp->left); if(tmp->right) connect(tmp->right); } };
Populating Next Right Pointers in Each Node II
标签:
原文地址:http://blog.csdn.net/u011412619/article/details/45955433