首页 > 其他 > 详细

LeetCode Populating Next Right Pointers in Each Node (技巧)

时间:2015-11-04 00:26:19      阅读:281      评论:0      收藏:0      [点我收藏+]

 

 

题意:

  给一棵满二叉树,要求将每层的节点从左到右用next指针连起来,层尾指向NULL即可。

 

思路:

  可以递归也可以迭代。需要观察到next的左孩子恰好就是本节点的右孩子的next啦。

 

  (1)递归:这个更快。

技术分享
 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void DFS(TreeLinkNode* root,TreeLinkNode* t)
12     {
13         if(root->next==NULL && t!=NULL)    root->next=t->left;
14         if(root->left)
15         {
16             root->left->next=root->right;
17             DFS(root->left, NULL);
18             DFS(root->right,root->next);
19         }
20     }
21     void connect(TreeLinkNode *root) {
22         if(root)    DFS(root,NULL);
23     }
24 };
AC代码

  (2)递归:这个简洁。

技术分享
 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void connect(TreeLinkNode *root) {
12         if(root && root->left)
13         {
14             root->left->next=root->right;
15             if(root->next)
16                 root->right->next=root->next->left;
17             connect(root->left);
18             connect(root->right);
19         }
20 
21         
22     }
23 };
AC代码

  (3)迭代:这个更吊。

 

 

  

LeetCode Populating Next Right Pointers in Each Node (技巧)

原文:http://www.cnblogs.com/xcw0754/p/4934614.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!