打印二叉树的边界节点-Java:标准二

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请轻击http://www.captainbed.net

package live.every.day.ProgrammingDesign.CodingInterviewGuide.BinaryTree;

public class PrintBinaryTreeBoundaryNodeStandard2 {

    public static class Node {
        public int data;
        public Node left;
        public Node right;

        public Node(int data) {
            this.data = data;
        }
    }

    public void printBoundaryNode(Node root) {
        if (root == null) {
            return;
        }
        System.out.print(root.data + " ");
        if (root.left != null && root.right != null) {
            printLeftBoundaryNode(root.left, true);
            printRightBoundaryNode(root.right, true);
        } else {
            printBoundaryNode(root.left != null ? root.left : root.right);
        }
        System.out.println();
    }

    public void printLeftBoundaryNode(Node root, boolean print) {
        if (root == null) {
            return;
        }
        if (print || (root.left == null && root.right == null)) {
            System.out.print(root.data + " ");
        }
        printLeftBoundaryNode(root.left, print);
        printLeftBoundaryNode(root.right, print && root.left == null);
    }

    public void printRightBoundaryNode(Node root, boolean print) {
        if (root == null) {
            return;
        }
        printRightBoundaryNode(root.left, print && root.right == null);
        printRightBoundaryNode(root.right, print);
        if (print || (root.left == null && root.right == null)) {
            System.out.print(root.data + " ");
        }
    }

}

你可能感兴趣的:(#,Coding,Interview,Guide,打印二叉树的边界节点)