LeetCode897. 递增顺序查找树

题目

法一、自己

 1 class Solution {
 2 public:
 3     vector<int>res;
 4     TreeNode* increasingBST(TreeNode* root) {
 5         dfs(root);
 6         TreeNode* p = new TreeNode(0);
 7         TreeNode *cur = p;
 8         for(int i =0;i <res.size();i++){
 9             cur->val = res[i];
10             //cur->right = new TreeNode(res[i]);
11             if(i == res.size()-1) break;
12             cur->right = new TreeNode();
13             cur = cur->right;
14         }
15         return p;
16     }
17     void dfs(TreeNode* root){
18         if(root!=NULL){
19             dfs(root->left);
20             res.push_back(root->val);
21             dfs(root->right);
22         }
23     }
24 };

没有一次bug free直接A掉的原因是又忘记自己经常犯得一个错误,经常空指针赋值。

第一次写,9-13行为 cur->val = res[i];   cur = cur->right;这样在循环里更新后的cur可能为空。

所以先要创建一个右节点然后更新指针。并且最后一次不需要创建右节点,所以在最后一次

循环控制。

法二、类似链表中的创造哑节点的思想,就是创建一个头节点,之后并不是对访问结点更新,

而是对它的右节点更新

 1 class Solution {
 2 public:
 3     vector<int>res;
 4     TreeNode* increasingBST(TreeNode* root) {
 5         dfs(root);
 6         TreeNode* p = new TreeNode(0);
 7         TreeNode *cur = p;
 8         for(int i =0;i <res.size();i++){
 9             cur->right = new TreeNode(res[i]);
10             cur = cur->right;
11         }
12         return p->right;
13     }
14     void dfs(TreeNode* root){
15         if(root!=NULL){
16             dfs(root->left);
17             res.push_back(root->val);
18             dfs(root->right);
19         }
20     }
21 };

一定要学习这种做法

posted @ 2021-01-13 16:08  Uitachi  阅读(69)  评论(0编辑  收藏  举报