day8
- 中序遍历
…..写了这么久还是写不对,累qwq1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>(); // 修改为 Stack<TreeNode> 类型 一个栈进行操作
List<Integer> result = new LinkedList<>(); //一个linkedlist进行记录
while(root != null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
result.add(root.val);
root = root.right;
}
return result;
}
} - 第k小的元素在二叉搜索树中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>(); // 修改为 Stack<TreeNode> 类型
List<Integer> result = new LinkedList<>();
int cnt = 0;
while(root != null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
result.add(root.val);
root = root.right;
}
return result.get(k-1); //LinkedList 直接用get方法
}
}
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment
WalineFacebook Comments