1. 程式人生 > >二叉搜尋樹中的第K大的節點 java實現

二叉搜尋樹中的第K大的節點 java實現

給定一顆二叉搜尋樹,請找出其中的第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));
    }
}