zoukankan      html  css  js  c++  java
  • 99. Recover Binary Search Tree(js)

    99. Recover Binary Search Tree

    Two elements of a binary search tree (BST) are swapped by mistake.

    Recover the tree without changing its structure.

    Example 1:

    Input: [1,3,null,null,2]
    
       1
      /
     3
      
       2
    
    Output: [3,1,null,null,2]
    
       3
      /
     1
      
       2
    

    Example 2:

    Input: [3,1,4,null,null,2]
    
      3
     / 
    1   4
       /
      2
    
    Output: [2,1,4,null,null,3]
    
      2
     / 
    1   4
       /
      3
    题意:保持结构不变,纠正使其成为合法的二叉搜索树
    代码如下:
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {void} Do not return anything, modify root in-place instead.
     */
    var recoverTree = function(root) {
        let list=[];
        let vals=[];
        inorder(root,vals,list);
        vals.sort((a,b)=>a-b);
        for(let i=0;i<list.length;i++){
            list[i].val=vals[i];
        }
    };
    var inorder=function(root,vals,list){
        if(!root) return ;
        inorder(root.left,vals,list);
        list.push(root);
        vals.push(root.val);
        inorder(root.right,vals,list);
    }
  • 相关阅读:
    PHP类(一)-类的实例化
    PHP函数(六)-匿名函数(闭包函数)
    PHP函数(五)-回调函数
    javaIO-字符流
    split 命令
    hadoop的增删改查
    Hadoop的MR
    java的序列化和反序列化
    字符串格式化-String类format方法
    Avro从入门到入土
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10707467.html
Copyright © 2011-2022 走看看