其他分享
首页 > 其他分享> > 2021.10.17 - 124.二叉搜索树中第K小的元素

2021.10.17 - 124.二叉搜索树中第K小的元素

作者:互联网

文章目录

1. 题目

在这里插入图片描述
在这里插入图片描述

2. 思路

(1) 中序遍历+递归

(2) 中序遍历+栈

3. 代码

import java.util.Deque;
import java.util.LinkedList;

public class Test {
    public static void main(String[] args) {
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

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

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    private int k = 0;
    private int res = -1;

    public int kthSmallest(TreeNode root, int k) {
        this.k = k;
        inorder(root);
        return res;
    }

    private void inorder(TreeNode root) {
        if (root == null || res >= 0) {
            return;
        }
        inorder(root.left);
        k--;
        if (k == 0) {
            res = root.val;
        }
        inorder(root.right);
    }
}

class Solution1 {
    public int kthSmallest(TreeNode root, int k) {
        Deque<TreeNode> stack = new LinkedList<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            k--;
            if (k == 0) {
                break;
            }
            root = root.right;
        }
        return root.val;
    }
}

标签:遍历,TreeNode,2021.10,17,int,val,124,right,root
来源: https://blog.csdn.net/qq_44021223/article/details/120808084