Flatten Binary Tree to Linked List @leetcode

=看完别人的代码,就无限接近于认为自己是沙茶。大家的思路怎么这么简洁,以至于我能看懂,我估计我的代码别人都看不懂。

 1 void flatten(TreeNode *root) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         TreeNode*tmp;
 5         flattenpiece(root,tmp);
 6     }
 7     void flattenpiece(TreeNode *root,TreeNode *&tail){
 8         if(root == NULL)
 9             return;
10         TreeNode*leftTreeRoot = root->left;
11         TreeNode*rightTreeRoot = root->right;
12         if(leftTreeRoot == NULL)
13         {
14             TreeNode*tmp;
15             flattenpiece(rightTreeRoot,tmp);
16             if(rightTreeRoot == NULL)
17                 tail = root;
18             else
19                 tail =tmp;
20             return;
21         }
22         //TreeNode*leftTreeTail;
23         flattenpiece(leftTreeRoot,tail);
24         root->right = leftTreeRoot;
25         root->left = NULL;
26         if(tail)
27         {
28             if(rightTreeRoot)
29             {
30                 tail->right = rightTreeRoot;
31                 tail->left = NULL;
32                 tail = rightTreeRoot;
33             }
34         }
35         flattenpiece(rightTreeRoot,tail);
36     }
37 }

=思路嗷嗷清晰的人的代码:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     void flatten(TreeNode *root) {
13         // IMPORTANT: Please reset any member data you declared, as
14         // the same Solution instance will be reused for each test case.
15         if (root == NULL) return;
16         if (root->left == NULL && root->right == NULL) {
17             return;
18         } else if (root->left == NULL) {
19             flatten(root->right);
20         } else if (root->right == NULL) {
21             root->right = root->left;
22             root->left = NULL;
23             flatten(root->right);
24         } else {
25             flatten(root->left);
26             flatten(root->right);
27             TreeNode* p = root->left;
28             while (p->right) {
29                 p = p->right;
30             }
31             p->right = root->right;
32             root->right = root->left;
33             root->left = NULL;
34          }
35     }
36 };

=我是弧度

posted @ 2013-11-14 17:41  沙茶面  阅读(135)  评论(0编辑  收藏  举报