zoukankan      html  css  js  c++  java
  • 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 };

    一定要学习这种做法

  • 相关阅读:
    ui自动化-则神第一天04-学习方法
    PHP unserialize()
    路径中 斜杠/和反斜杠 的区别
    PhpStorm 克隆下来的项目改动,版本控制不起效果
    PhpStorm 回到上次编辑位置的快捷键
    mysql max_allowed_packet查询和修改
    PHP大批量插入数据库的3种方法和速度对比
    mysql5.7.23安装详细过程
    JS 放大镜
    aviary 图片编辑器
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14272650.html
Copyright © 2011-2022 走看看