앞뒤로 두 갈래 나무를 두루 다니다

2555 단어 두루 다니다
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

public class traversal {

    public static void main(String[] args) {

        TreeNode t = CreateTree();

        dfs(t);

    }

    // 
    public static void dfs(TreeNode root) {
        if (root == null) {
            return;
        }

        System.out.println(root.val);

        dfs(root.left);
        dfs(root.right);

    }

    public static TreeNode CreateTree() {

        TreeNode t1 = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        TreeNode t3 = new TreeNode(3);
        TreeNode t4 = new TreeNode(4);
        TreeNode t5 = new TreeNode(5);
        TreeNode t6 = new TreeNode(6);
        TreeNode t7 = new TreeNode(7);
        TreeNode t8 = new TreeNode(8);
        TreeNode t9 = new TreeNode(9);
        TreeNode t10 = new TreeNode(10);

        t1.left = t2;
        t1.right = t3;
        t2.left = t4;
        t2.right = t5;
        t4.left = t7;
        t4.right = t8;
        t8.right = t10;
        t3.left = t6;
        t6.left = t9;

        return t1;
    }
}

좋은 웹페이지 즐겨찾기