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 };
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 };
时间: 2024-10-23 09:41:23