Populating Next Right Pointers in Each Node II
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
/** * 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) {} * }; */ //因此,对一个节点需要向右找到第一个节点。 //对于left,如果right不存在,就在father的next节点去找left/right,依次找下去。 //对于right,直接在father的next节点开始找。 // //需要注意的是,要先处理右子树,再处理左子树。 class Solution { TreeLinkNode *node; public: void connect(TreeLinkNode *root) { if(root) { if(root->left) { if(root->right) root->left->next = root->right; else { node = root->next; while( node && !root->left->next) { if(node->left) root->left->next = node->left; else if(node->right) root->left->next = node->right; node = node->next; } } } if(root->right) { node = root->next; while(node && root->right->next==NULL) { if(node->left) root->right->next = node->left; else if(node->right) root->right->next = node->right; node = node->next; } } connect(root->right); connect(root->left); } } };
//另一种写法 class Solution { public: void connect(TreeLinkNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL) return ; root->next = NULL; TreeLinkNode* prevHead = root; while(true) { TreeLinkNode* cur = prevHead; TreeLinkNode* prev = NULL; while(cur != NULL) { if(cur->left != NULL) { if(prev != NULL) prev->next = cur->left, prev = prev->next; else prev = cur->left, prevHead = prev; } if(cur->right != NULL) { if(prev != NULL) prev->next = cur->right, prev = prev->next; else prev = cur->right, prevHead = prev; } cur = cur->next; } if(prev != NULL) prev->next = NULL; else break; } } };
leetcode_117_Populating Next Right Pointers in Each Node II
原文地址:http://blog.csdn.net/keyyuanxin/article/details/44115361