226. 翻转二叉树
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
备注:
这个问题是受到 Max Howell 的 原问题 启发的 :
谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
我的答案
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
Stack<TreeNode> stack = new Stack();
TreeNode temp=null,next = root;
do{
temp = next.left;
next.left = next.right;
next.right = temp;
if(next.left!=null){
if(next.right!=null){
stack.add(next.right);
}
next = next.left;
}else if(next.right!=null){
next = next.right;
}else{
if(stack.isEmpty()){
break;
}
next = stack.pop();
}
} while(!stack.isEmpty() || next.left!=null || next.right!=null);
return root;
}
}
剑指Offer 40. 最小的k个数
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
示例 1:
输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]
示例 2:
输入:arr = [0,1,2,1], k = 1
输出:[0]
限制:
0 <= k <= arr.length <= 10000
0 <= arr[i] <= 10000
我的答案
使用的优先队列
class Solution {
public int[] getLeastNumbers(int[] arr, int k) {
if(k==0){
return new int[0];
}
int[] res = new int[k];
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i=0;i<k;i++) {
pq.add(-arr[i]);
}
for(int i=k;i<arr.length;i++) {
if(-arr[i]>pq.peek()) {
pq.poll();
pq.add(-arr[i]);
}
}
for(int i=0;i<k;i++) {
res[i] = -pq.poll();
}
return res;
}
}