LeetCode HOT 100 记录

230. 二叉搜索树中第 K 小的元素 - 力扣(LeetCode)

相当于把二叉搜索树从小到大排序,而二叉搜索树有一个特点,就是顺序左子树 < 根节点 < 右子树,因此可以考虑使用中序遍历

/**
 * Definition for a binary tree node.
 * public 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 {
    int now = 0;
    int ans = 0;
    
    public int kthSmallest(TreeNode root, int k) {
        find(root, k);
        return ans;
    }

    public void find(TreeNode root, int k) {
        if (root == null) {
            return;
        }
        find(root.left, k);
        if (++now == k) {
            ans = root.val;
            return;
        }
        find(root.right, k);
    }

}

199. 二叉树的右视图 - 力扣(LeetCode)

按照中 -> 右 -> 左遍历,只要每层记录一下第一个遍历到的节点

/**
 * Definition for a binary tree node.
 * public 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 {

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        find(root, ans, 0);
        return ans;
    }

    public void find(TreeNode root, List<Integer> ans, int now) {
        if (root == null) {
            return ;
        }
        if (ans.size() <= now) {
            ans.add(root.val);
        }
        find(root.right, ans, now+1);
        find(root.left, ans, now+1);
    }

}
posted @ 2024-11-07 23:27  MMMMMMMW  阅读(1)  评论(0编辑  收藏  举报