问题:
给你一个complete 二叉树,逆时针打印所有边缘节点, 比如:
那么,逆时针打印边缘节点后,输出:1 , 3, 5, 9, 8, 6 .
分析:
如果想写一个方法实现这个要求是很难的,但是,我们可以考虑分步实现。
第一步:打印左边的边缘节点;
第二步:打印底部所有节点;
第三步:打印右边所有边缘节点。
代码如下:
- public static void printLeft(Node root) {
- if (root.leftChild != null || root.rightChild != null) {
- print(root);
- printLeft(root.leftChild);
- }
- }
- public static void printButtom(Node root) {
- if (root != null) {
- if (root.leftChild == null && root.rightChild == null) {
- print(root);
- }
- printButtom(root.leftChild);
- printButtom(root.rightChild);
- }
- }
- public static void printRight(Node root, Node node) {
- if (root.leftChild != null || root.rightChild != null) {
- printRight(root.rightChild, node);
- // do not print the root again
- if (root != node) {
- print(root);
- }
- }
- }