62. 二叉搜索樹的第k個節點

題目描述

給定一棵二叉搜索樹,請找出其中的第k小的結點。例如, (5,3,7,2,4,6,8) 中,按結點數值大小順序第三小結點的值爲4。

Solution

二叉搜索樹(二叉排序樹)左子樹比根小,右子樹比根大
中序遍歷的順序就是升序排序的結果,第k個節點即爲第k小節點

  1. 遞歸中序遍歷
public class Solution {
		int index = 0;  //計數器
		//遞歸中序遍歷
	    TreeNode KthNode(TreeNode pRoot, int k)
	    {
	    	if (pRoot != null) {
	    		TreeNode node = KthNode(pRoot.left, k);
	    		if (node != null) {    //找到node後一級一級向上返回
	    			return node;
	    		}
	    		index++;
	    		if (index == k) {
	    			return pRoot;
	    		}
	    		node = KthNode(pRoot.right, k);
	    		if (node != null) {
	    			return node;
	    		}
	    	}
	    	return null;   //node爲null或還未找到都返回null      
	    }
	}
  1. 非遞歸中序遍歷,棧存儲經過的節點
public class Solution {
		//非遞歸中序遍歷
	    TreeNode KthNode(TreeNode pRoot, int k)
	    {
	    	Stack<TreeNode> s = new Stack<>();
	    	int i = 0;
	    	TreeNode node = pRoot;
	    	while (!s.empty() || node != null) {
	    		if (node != null) {
	    			s.push(node);  //左子樹一路往下壓棧
	    			node = node.left;
	    		} else {
	    			node = s.pop();  //判斷當前根節點
	    			i++;
	    			if (i == k) {  
	    				return node;
	    			}
	    			node = node.right;  //右子樹壓棧
	    		}	
	    	}
	    	return null;
	    }
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章