标签:== incr col return http 技术 nbsp 查找 中序遍历
题目:
解答:
方法一:中序遍历 + 构造新的树
我们在树上进行中序遍历,就可以从小到大得到树上的节点。我们把这些节点的对应的值存放在数组中,它们已经有序。接着我们直接根据数组构件题目要求的树即可。
1 /** 2 * Definition for a binary tree node. 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 13 void inorder(TreeNode *root, vector<int> &ret) 14 { 15 if (NULL == root) 16 { 17 return; 18 } 19 20 inorder(root->left, ret); 21 ret.push_back(root->val); 22 inorder(root->right, ret); 23 } 24 25 TreeNode* increasingBST(TreeNode* root) 26 { 27 vector<int> result; 28 inorder(root, result); 29 30 TreeNode *ans = new TreeNode(0); 31 TreeNode *cur = ans; 32 for (int v: result) 33 { 34 cur->right = new TreeNode(v); 35 cur = cur->right; 36 } 37 return ans->right; 38 39 } 40 };
标签:== incr col return http 技术 nbsp 查找 中序遍历
原文地址:https://www.cnblogs.com/ocpc/p/12822099.html