Kth smallest node of binary search tree

topic:

Given a binary search tree, please find the k-th smallest node in it.
Input: {5,3,7,2,4,6,8},3
Return value: {4}
Description: The value of the third small node is 4 in order of the numerical value of the node

Ideas:

  1. First of all, the binary search tree is characterized by small left and large right, so if it is a middle-order traversal, it is exactly an ascending sequence
  2. So we can count at the same time on the basis of in-order traversal, Kth smallest = Kth from smallest to largest

Code:

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    
    
    private int count = 0;
    TreeNode KthNode(TreeNode pRoot, int k) {
    
    
        if(pRoot == null || k <= 0) return null;
        return dfs(pRoot, k);
    }
    
    private TreeNode dfs(TreeNode root, int k){
    
    
        if(root==null) return null;
        TreeNode left = dfs(root.left, k);
        if (left!=null) return left;
        count++;
        if(count==k) return root;
        return dfs(root.right, k);
    } 

}

Guess you like

Origin blog.csdn.net/qq_35221523/article/details/110762007