ZhengXingchi / ZhengXingchi.github.io

Apache License 2.0
0 stars 0 forks source link

剑指offer(62)二叉搜索树的第K个节点 #41

Open ZhengXingchi opened 4 years ago

ZhengXingchi commented 4 years ago

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

   function KthNode(root, k) {
      if (root === null || k === 0) {
        return null
      }
      function KthNodeCore(node) {
        let target = null
        if (node.left) {
          target = KthNodeCore(node.left)
        }
        if (target === null) {
          if (k === 1) {
            target = node
          }
        }
        if (target === null && node.right) {
          target = KthNodeCore(node.right)
        }
        return target
      }
      return KthNodeCore(root)
    }
ZhengXingchi commented 4 years ago

参考文献

二叉树遍历(先序、中序、后序)