给定一棵二叉搜索树,请找出其中的第 k 小的结点


解题思路

根据二叉搜索树的性质,按照中序遍历的顺序打印出来正好就是排序好的顺序,所以,按照中序遍历顺序找到第 k个结点就是结果

在遍历过程中,如果发现有符合条件的结点,则直接递归向上返回,因此返回的 node 必然不为空,正好符合判断条件。如果不做 node 是否为 null 的判断,则目标结点会被其父结点所覆盖

public class Solution {
    
    int count = 1;
    TreeNode KthNode(TreeNode pRoot, int k) {
        if(pRoot != null) {
            TreeNode node = KthNode(pRoot.left, k);
            if(node != null) {
                return node;
            }
            if(count == k) {
                return pRoot;
            }
            count++;
            node = KthNode(pRoot.right, k);
            if(node != null) {
                return node;
            }
        }
        return null;
    }
}

相关文章:

  • 2021-08-04
  • 2021-10-18
  • 2022-12-23
  • 2022-12-23
  • 2021-06-07
  • 2021-06-29
  • 2022-12-23
  • 2021-05-13
猜你喜欢
  • 2021-09-18
相关资源
相似解决方案