二叉搜索树中的第K大的节点 java实现

来源:互联网 发布:js div隐藏与显示 编辑:程序博客网 时间:2024/04/28 09:44

题目描述

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

解题思路:因为这是一颗二叉搜索树,返回的第K个节点其实就是二叉树按中序遍历的第K个节点。

思路一:按中序遍历顺序,将节点一个一个存在LinkedList中,存完之后,取出第k个节点就行啦,这个方法有点low啦

思路二:仍然是按中序遍历,不过,(1)先看节点的左子树节点数和K作比较,如果比k小,说明第K个节点在根节点或者在根节点的右子树上,在找右子树之前先看看看右子树的节点数是否小于(k-左子树节点数-1),如果小于说明找不到第K个节点啦,因为所有节点加起来都不到K个。如果大于的话,那就可以在右子树上找啦。(2)如果左子树节点大于K,那就应该爱左子树上查找啦

思路三:思路一就是遍历所有节点然后找出第K个节点,所有的节点只遍历一次,但是需要O(n)的空间复杂度;思路二,不要要额外的空间,但是在查过过程中是从根节点开始查的,所以节点的遍历次数不止一次;那我们最好想只用O(1)空间复杂度,然后最好所有节点只遍历一次。那么,这种思路应该从底部向上遍历,从最下面的左节点开始。

3种思路的代码如下:

思路一:

import java.util.LinkedList;class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}public class KthNode {    public LinkedList<TreeNode> list = new LinkedList<TreeNode>();    TreeNode KthNode(TreeNode pRoot, int k)    {    startBuildList(pRoot);    if(list.size() < k || k < 1) return null;    else {    return list.get(k-1);    }    }        public void startBuildList(TreeNode root) {    if (root == null) return;    if (root.left != null) {    startBuildList(root.left);    }    list.add(root);    if (root.right != null) {    startBuildList(root.right);    }    }}

思路二:

import java.util.LinkedList;class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}public class KthNode {TreeNode KthNode(TreeNode pRoot, int k){    if(k < 1 || pRoot == null) return null;    //左子树节点个数int leftCount = getNodeCount(pRoot.left);if(leftCount < k ){if((leftCount+1) == k)//根节点就是我们要找的节点return pRoot;else {//开始从右子树找节点            if (getNodeCount(pRoot.right) < (k-leftCount-1)) return null;return KthNode(pRoot.right, k-(leftCount+1));}} else {//在左子树中找return KthNode(pRoot.left, k);}}public int getNodeCount(TreeNode root) {if (root == null) return 0;int count = 0;count = getNodeCount(root.left) + getNodeCount(root.right) + 1;return count;}}

思路三:

import java.util.*;class Temp {    public int val;    Temp(int val) {        this.val = val;    }}public class Solution {    TreeNode findKth (TreeNode pRoot, Temp k) {        if (k.val <1 || pRoot == null) return null;        TreeNode target = null;        if (pRoot.left != null) {            target = findKth(pRoot.left,k);        }        if (target == null) {            if (k.val == 1) {                target = pRoot;            }            k.val--;        }        if (target == null && pRoot.right != null) {            target = findKth(pRoot.right, k);        }        return target;    }    TreeNode KthNode(TreeNode pRoot, int k)    {        return findKth(pRoot,new Temp(k));    }}


原创粉丝点击