码迷,mamicode.com
首页 > 其他好文 > 详细

9.21-9.27

时间:2015-09-21 09:12:20      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

1.Flatten Binary Tree to Linked List

技术分享
 1 //dfs、前序遍历一下即可
 2 class Solution {
 3 public:
 4     void dfs(TreeNode* root, TreeNode* &pre)
 5     {
 6         if (root == NULL) return ;
 7         pre->left = root;
 8         pre = pre->left;
 9         if (root->left) dfs(root->left, pre);
10         if (root->right) dfs(root->right, pre);
11     }
12     void work(TreeNode *root)
13     {
14         if (root == NULL) return;
15         if (root->left) work(root->left);
16         root->left = NULL;
17     }
18     void flatten(TreeNode* root) {
19         if (root == NULL) return ;
20         TreeNode* tmp = new TreeNode(-1);
21         dfs(root, tmp);
22         TreeNode *t = root;
23         while (t)
24         {
25             t->right = t->left;
26             t = t->left;
27         }
28         t = root;
29         work(t);
30     }
31 };
View Code

 2.Convert Sorted List to Binary Search Tree

技术分享
 1 //递归,根据postorder来做,postorder最后一个值肯定是root,根据这个来做即可。
 2 class Solution {
 3 public:
 4     TreeNode* build(vector<int>& inorder, vector<int>& postorder, int left1, int right1, int left2, int right2)
 5     {
 6         if (left1 > right1) return NULL;
 7         TreeNode *tmp = new TreeNode(postorder[right2]);
 8         if (left1 == right1)
 9             return tmp;
10         int i, j;
11         for (i = right1; i >= left1; --i)
12             if (inorder[i] == postorder[right2]) break;
13         tmp->right = build(inorder, postorder, i+1, right1, right2-1-(right1-i-1), right2-1);
14         tmp->left = build(inorder, postorder, left1, i-1, left2, right2-1-(right1-i-1)-1); 
15     }
16     
17     TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
18         return build(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1);
19     }
20 };
View Code

 

9.21-9.27

标签:

原文地址:http://www.cnblogs.com/JustForCS/p/4825154.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!