1. 程式人生 > >面試題:二叉搜索樹的第K個節點

面試題:二叉搜索樹的第K個節點

color util 順序 tree ++ turn 大小 k個結點 tac

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

思路1:非遞歸中序遍歷

import java.util.Stack;
public class Solution {
    TreeNode KthNode(TreeNode root, int k){
        if(root==null||k==0) return null;
        int count=0;
        Stack<TreeNode> stack=new Stack<>();
        
while(root!=null||!stack.isEmpty()){ while (root != null) { stack.push(root); root = root.left; } root=stack.pop(); count++; if(count==k) return root; root=root.right; } return null
; } }

思路2:遞歸中序遍歷 這個不是很懂

//思路:二叉搜索樹按照中序遍歷的順序打印出來正好就是排序好的順序。
//     所以,按照中序遍歷順序找到第k個結點就是結果。
public class Solution {
   int index = 0; //計數器
    TreeNode KthNode(TreeNode root, int k)
    {
        if(root != null){ //中序遍歷尋找第k個
            TreeNode node = KthNode(root.left,k);
            if(node != null
) return node; index ++; if(index == k) return root; node = KthNode(root.right,k); if(node != null) return node; } return null; } }

面試題:二叉搜索樹的第K個節點