[leetcode] Populating Next Right Pointers in Each Node II
来源:互联网 发布:企业整站源码 编辑:程序博客网 时间:2024/06/07 18:50
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思路:与Populating Next Right Pointers in Each Node类似,采用递归,只是需要处理一些特殊情况
代码:
/** * 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) { TreeLinkNode *temp; int flag=0; if(root == NULL) return; if(root->left != NULL){ temp=root; flag=0; while(temp!=NULL){ if(temp->left!=NULL && temp->left!=root->left){ root->left->next=temp->left; flag=1; break; } if(temp->right!=NULL){ root->left->next=temp->right; flag=1; break; } temp=temp->next; } if(flag==0) root->left->next=NULL; } if(root->right !=NULL){ flag=0; temp=root->next; while(temp!=NULL){ if(temp->left!=NULL){ root->right->next=temp->left; flag=1; break; } if(temp->right!=NULL){ root->right->next=temp->right; flag=1; break; } temp=temp->next; } if(flag==0) root->right->next=NULL; } connect(root->right); connect(root->left); }};
0 0
- 【LeetCode】Populating Next Right Pointers in Each Node 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 79: 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] 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 | Populating Next Right Pointers in Each Node II
- [leetcode]Populating Next Right Pointers in Each Node II
- 【LeetCode OJ】Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node II
- OCP 1Z0 053 155
- 关于UINavigationController
- 18.1.1 目录列表器
- JAVA8 十大新特性详解
- xcode编译错误总结
- [leetcode] Populating Next Right Pointers in Each Node II
- 写具有Objective-C特征的Swift类—Swift学习笔记(二十一)
- python抓取百度热词
- HTTP POST GET详解
- 紐巴倫 UPSSDv5jg
- 耐克官網 oRTTMd2qt
- JSP页面怎样调用Spring配置文件中定义的Bean
- iOS毛玻璃
- xcode编译后无法找到xx文件的错误解决办法