Sword refers to Offer-59-the Kth node of the binary search tree

Title description

Given a binary search tree, please find the k-th smallest node in it. For example, in (5,3,7,2,4,6,8), the value of the third small node is 4 in the order of node value.

Idea analysis

The characteristics of the binary search tree are: the left node is larger than the root node, and the right node is smaller than the root node.
The result of the middle order traversal is: left-"middle-" right
The combination of the two is an ordered sequence.

Code

import java.util.ArrayList;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {
    
    
    ArrayList<TreeNode> list = new ArrayList<>();
    TreeNode KthNode(TreeNode pRoot, int k)
    {
    
    
        KthHelper(pRoot);   
        if(k>=1&&k<=list.size()){
    
    
            return list.get(k-1);
        }
        return null;
    }
    //使用中序遍历:左 中 右
    void KthHelper(TreeNode root){
    
    
        if(root!=null){
    
    
        KthHelper(root.left);
        list.add(root);
        KthHelper(root.right);
        }
    }


}

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107593418