题目:打印中序遍历指定节点的后续节点
思路:两种情况当前节点右子树是否为null,如果不是返回右子树最左非空子节点,否则往上找,直到父节点为空或者当前节点是父节点的左子树,返回父节点
public class Code06_SuccessorNode {public static Node getSuccessorNode(Node node) {if(node== null)return null;// 中序遍历 当前节点的后续节点if(node.right != null){Node cur = node.right;while (cur.left != null){cur = cur.left;}return cur;}else{Node cur = node;Node parent = cur.parent;while (parent != null && parent.right == cur){cur = parent;parent = parent.parent;}return parent;}}
}
题目:请把一段纸条竖着放在桌子上,然后从纸条的下边向上方对折1次,压出折痕后展开。此时折痕是凹下去的,即折痕突起的方向指向纸条的背面。 如果从纸条的下边向上方连续对折2次,压出折痕后展开,此时有三条折痕,从上到下依次是下折痕、下折痕和上折痕。
给定一个输入参数N,代表纸条都从下边向上方连续对折N次。 请从上到下打印所有折痕的方向。
例如:N=1时,打印: down N=2时,打印: down down up
思路:观察法
// 折叠n打印凹凸序列public static void p(int n){if (n ==0)System.out.println("");// 1 整个折痕个数 然后直接计算各个位置应该打印的字符串// 2 肯定是奇数个,从中间开始向两边赋值 每次赋值就是一层,有多少层(折叠多少次)遍历多少次int l = (int)Math.pow(2,n)-1;String[] a = new String[l];process(a,0,l-1,"凹");for (String s : a) {System.out.print(s+" ");}}// todo转换为非递归方式/*** 对二叉树先序遍历,将字符串放在所在范围的中间位置 观察法* @param a 存放数据的* @param start 整个数组开始位置* @param end 数组结束位置* @param str 当前节点应该打印的字符串*/public static void process(String[] a,int start ,int end,String str){if(start == end){a[start] = str;return;}// 计算当前应该放在的位置int m = (start+end)/2;a[m] = str;process(a,start,m-1,"凹");process(a,m+1,end,"凸");}