1.排序栈
给定一个乱序的栈,设计一个算法将其升序排列,可以使用一个辅助栈
public class Solution {
public Stack<Integer> sort(Stack<Integer> stack) {
int tmp = 0;
Stack<Integer> tmpStack = new Stack<>();
while (!stack.isEmpty()) {
int num = stack.pop();
if (tmpStack.isEmpty() || tmpStack.peek() < num) {
tmpStack.add(num);
} else {
tmp = num;
int count = 0;
while (!tmpStack.isEmpty() && tmpStack.peek() > num) {
stack.add(tmpStack.pop());
count++;
}
tmpStack.add(tmp);
while (count-- > 0) {
tmpStack.add(stack.pop());
}
}
}
return tmpStack;
}
public static void main(String[] args) {
Solution s = new Solution();
Stack<Integer> stack = new Stack<>();
stack.add(4);
stack.add(2);
stack.add(1);
stack.add(3);
Stack<Integer> sort = s.sort(stack);
while (!sort.isEmpty()) {
System.out.print(sort.pop());
}
}
}
有点像汉诺塔。
2.从左到右遍历二叉树的叶子节点
public class Solution {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode() {
}
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode node5 = new TreeNode(5);
TreeNode node7 = new TreeNode(7);
TreeNode node10 = new TreeNode(10);
TreeNode node6 = new TreeNode(6, node5, node7);
TreeNode node8 = new TreeNode(8, node6, node10);
List<Integer> leaf = solution.leaf(node8);
for (Integer i : leaf) {
System.out.println(i);
}
// 输出 5 7 10
}
public List<Integer> leaf(TreeNode root) {
if (root == null) {
return null;
}
List<Integer> res = new ArrayList<>();
dfs(root, res);
return res;
}
private void dfs(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
res.add(root.val);
}
dfs(root.left, res);
dfs(root.right, res);
}
}