leetcode116 Populating Next Right Pointers in Each Node
2015-07-13 21:09
651 查看
题意:给一个完全二叉树:
让左子树的next指针指向右子树,右子树的next继续指向右边,变成了这样:
思路:唉,英语不行真是醉了,半天没弄明白题意,最后没办法了去找了别人的博客看才明白要干啥。这题的特殊点在于树是完全二叉树,对于其中的一个节点p来说,p->left->next = p->right;p->right->next = p->next->left;明白了这两点这题就解决了,可以用递归,即对root进行这样的操作再对root->left和root->right再做一遍;也可以迭代,附上两种方法的代码。
此题不错,应该多注意一下。
代码1 递归:
代码2 迭代:
1 / \ 2 3 / \ / \ 4 5 6 7
让左子树的next指针指向右子树,右子树的next继续指向右边,变成了这样:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
思路:唉,英语不行真是醉了,半天没弄明白题意,最后没办法了去找了别人的博客看才明白要干啥。这题的特殊点在于树是完全二叉树,对于其中的一个节点p来说,p->left->next = p->right;p->right->next = p->next->left;明白了这两点这题就解决了,可以用递归,即对root进行这样的操作再对root->left和root->right再做一遍;也可以迭代,附上两种方法的代码。
此题不错,应该多注意一下。
代码1 递归:
void connect(TreeLinkNode *root) { if(root == NULL) return; if(root->next && root->right) root->right->next = root->next->left; if(root->left) root->left->next = root->right; connect(root->left); connect(root->right); }
代码2 迭代:
void connect(TreeLinkNode *root) { TreeLinkNode *pre = root; TreeLinkNode *cur = NULL; while(pre) { cur = pre; while(cur && cur->left) { cur->left->next = cur->right; if(cur->next) cur->right->next = cur->next->left; cur = cur->next; } pre = pre->left; } }
相关文章推荐
- Node:快速排序
- Node:普通归并
- NodeJS
- hadoop namenode重新格式化以后hbase的hmaster进程启动后马上消失
- hadoop 格式化后没有datanode节点
- node 小结
- NodeJS学习第一季-字符串转换
- leetcode 025 —— Reverse Nodes in k-Group
- nodejs-2:模块与包管理工具
- 多次格式化namenode之后datanode无法启动
- NodeJS学习第一季-URL操作
- leetcode 024 —— Swap Nodes in Pairs
- NodeJS学习第一季-文件I/O
- XML的SelectNodes使用方法以及XPath
- NodeJS学习第一季-Process
- 工作节点配置
- The method getTextContent() is undefined for the type Node
- [INS-40901] The cluster node information table is unfilled 解决方案
- node.js(一)
- node.js安装