Populating Next Right Pointers in Each Node II <leetcode>
2014-09-09 18:58
337 查看
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,
After calling your function, the tree should look like:
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 算法:该题和第一个题的变种,不过揭发是一样的,首先也是只要考虑当前节点,然后递归就行了,要点有二:1、当该节点左子树或右子树的右边的第一个节点 2、递归时要先算右子树,因为左子树的处理递归时会用到右边已经形成的结果,代码如下:
/** * 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(NULL==root) return; if(NULL!=root->left) { if(NULL!=root->right) { root->left->next=root->right; } else root->left->next=find(root->next); } if(NULL!=root->right) { root->right->next=find(root->next); } connect(root->right); connect(root->left); } TreeLinkNode* find(TreeLinkNode *temp) { if(NULL==temp) return NULL; while(NULL!=temp) { if(NULL!=temp->left) return temp->left; else if(NULL!=temp->right) return temp->right; else temp=temp->next; } return NULL; } };
相关文章推荐
- [LeetCode] Populating Next Right Pointers in Each Node II 解题报告
- 【leetcode】Populating Next Right Pointers in Each Node II
- [LeetCode 116 117] - 填充每一个节点的指向右边邻居的指针I & II (Populating Next Right Pointers in Each Node I & II)
- [LeetCode]Populating Next Right Pointers in Each Node II
- LeetCode | Populating Next Right Pointers in Each Node II
- leetcode 79: Populating Next Right Pointers in Each Node II
- LeetCode(Oct28'12):Populating Next Right Pointers in Each Node II
- leetcode Populating Next Right Pointers in Each Node II
- [leetcode刷题系列]Populating Next Right Pointers in Each Node II
- LeetCode-Populating Next Right Pointers in Each Node II
- LeetCode - Populating Next Right Pointers in Each Node II
- leetcode_question_117 Populating Next Right Pointers in Each Node II
- leetcode--Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node II
- [LeetCode 116 117] - 填充每一个节点的指向右边邻居的指针I & II (Populating Next Right Pointers in Each Node I & II)
- [leetcode] Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II [Leetcode]
- [Leetcode] Populating Next Right Pointers in Each Node ii
- leetcode 79: Populating Next Right Pointers in Each Node II
- LeetCode:Populating Next Right Pointers in Each Node I,II 编程之美3.10