May LeetCoding Challenge20 之 二叉树中序遍历
作者:互联网
因为题目为二叉搜索树找到第k大的数,所以对二叉搜索树中序遍历一定是有序的。
分为两种:递归 和 迭代(栈)
JAVA
/** * 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 LinkedList<Integer> inorder(TreeNode root, LinkedList<Integer> arr){ if(root == null) return arr; inorder(root.left, arr); arr.add(root.val); inorder(root.right, arr); return arr; } public int kthSmallest(TreeNode root, int k) { LinkedList<Integer> nums = inorder(root, new LinkedList<>()); return nums.get(k-1); } }
标签:LeetCoding,right,TreeNode,val,May,arr,int,二叉树,root 来源: https://www.cnblogs.com/yawenw/p/12944367.html