Chinaunix首页 | 论坛 | 博客
  • 博客访问: 40227
  • 博文数量: 37
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 372
  • 用 户 组: 普通用户
  • 注册时间: 2013-10-12 23:27
文章分类

全部博文(37)

文章存档

2014年(5)

2013年(32)

我的朋友

分类: C/C++

2013-12-10 10:54:05


点击(此处)折叠或打开

  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) return;
  13.         if(root->left&&root->right) root->left->next=root->right;
  14.         if(root->next)
  15.         {
  16.             TreeLinkNode *tmp=root->right?root->right:root->left;
  17.             if(tmp)
  18.             {
  19.                 TreeLinkNode *tmp2=root->next;
  20.                 while(tmp2)
  21.                 {
  22.                     if(tmp2->left||tmp2->right) break;
  23.                     tmp2=tmp2->next;
  24.                 }
  25.                 if(tmp2) tmp->next=tmp2->left?tmp2->left:tmp2->right;
  26.             }
  27.         }
  28.         if(root->right) connect(root->right);
  29.         if(root->left) connect(root->left);
  30.     }
  31. };

阅读(124) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~