1 题目
2 Java
中序遍历的延伸
2.1 方法一(中序遍历,迭代)
最傻的办法,没啥可说的
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthLargest(TreeNode root, int k) {
List<Integer> list = helper(root);
return list.get(list.size() - k);
}
public List<Integer> helper(TreeNode root){
List<Integer> list = new LinkedList<>();
if(root == null) return list;
list.addAll(helper(root.left));
list.add(root.val);
list.addAll(helper(root.right));
return list;
}
}
2.2 方法二(迭代)
和中序遍历的迭代方法基本一样,以右根左的顺序(中序逆过去)遍历树
遍历顺序即从大到小的顺序
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthLargest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode ans = root;
int index = 0;
while((!stack.isEmpty() || root != null) && index < k){
if(root != null){
stack.push(root);
root = root.right;
}
else{
ans = stack.pop();
index++;
root = ans.left;
}
}
return ans.val;
}
}
2.3 方法三(反中序遍历递归,多一行)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthLargest(TreeNode root, int k) {
helper(root, k);
return kNode.val;
}
TreeNode kNode;
int count;
public void helper(TreeNode root, int k){
if(root == null) return;
helper(root.right, k);
// 若当前节点root是第k大节点,记录结果
count++;
if(count == k) kNode = root;
helper(root.left, k);
}
}