LeetCode-897. Increasing Order Search Tree
阿新 • • 發佈:2018-12-21
Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
Example 1: Input: [5,3,6,2,4,null,8,1,null,null,null,7,9] 5 / \ 3 6 / \ \ 2 4 8 / / \ 1 7 9 Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] 1 \ 2 \ 3 \ 4 \ 5 \ 6 \ 7 \ 8 \ 9
Note:
- The number of nodes in the given tree will be between 1 and 100.
- Each node will have a unique integer value from 0 to 1000.
題解:好坑啊。。。一直以為輸入是二叉排序樹。。。題目也不講清楚
dfs瘋狂WA
class Solution { public: TreeNode* increasingBST(TreeNode* root) { TreeNode *p = root; vector<int> v; if (p == NULL) { return NULL; } else { dfs(p, v); } for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; } sort(v.begin(), v.end()); TreeNode *q = new TreeNode(v[0]); TreeNode *ans = q; for (int i = 1; i < v.size(); i++) { q->right = new TreeNode(v[i]); q = q->right; } return ans; } void dfs(TreeNode *p, vector<int> &v) { if (p != NULL) { v.push_back(p->val); dfs(p->left, v); dfs(p->right, v); } } };
中序遍歷ok了
class Solution { public: TreeNode* increasingBST(TreeNode* root) { TreeNode *p = root; vector<int> v; if (p == NULL) { return NULL; } else { inorder(p, v); } TreeNode *q = new TreeNode(v[0]); TreeNode *ans = q; for (int i = 1; i < v.size(); i++) { q->right = new TreeNode(v[i]); q = q->right; } return ans; } void inorder(TreeNode *p, vector<int> &v) { if (p != NULL) { inorder(p->left, v); v.push_back(p->val); inorder(p->right, v); } } };