zoukankan      html  css  js  c++  java
  • 树---二叉搜索树的第K个节点

    给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

    分析:二叉搜索树就是每个节点X,大于其左子树的值,小于其右子树的值,其中序排序是递增的。使用中序遍历,每遍历一个节点,k-1,直到k减到1,即为第K小的节点

    /* function TreeNode(x) {
    
        this.val = x;
    
        this.left = null;
    
        this.right = null;
    
    } */
    
    function KthNode(pRoot, k) {
    
      if (pRoot === null || k === 0) {
    
        return null;
    
      }
    
      // 为了能追踪k,应该把KthNodeCore函数定义在这里面,k应该在KthNodeCore函数外面
    
      function KthNodeCore(pRoot) {
    
        let target = null;
    
        if (pRoot.left !== null) {
    
          target = KthNodeCore(pRoot.left, k);
    
        }
    
        if (target === null) {
    
          if (k === 1) {
    
            target = pRoot;
    
          }
    
          k--;
    
        }
    
        if (target === null && pRoot.right !== null) {
    
          target = KthNodeCore(pRoot.right, k);
    
        }
    
        return target;
    
      }
    
      return KthNodeCore(pRoot);
    
    }
  • 相关阅读:
    Objective-C中的封装、继承、多态、分类
    C语言知识总结(5)
    C语言知识总结(4)
    C语言知识总结(3)
    C语言知识总结(2)
    C语言知识总结(1)
    H5-定位
    H5——浮动及清浮动
    H5基础标签
    H5盒模型基础
  • 原文地址:https://www.cnblogs.com/mlebk/p/12651419.html
Copyright © 2011-2022 走看看