226. 翻转二叉树

package sy5;

public class Test {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(7);
        TreeNode node3 = new TreeNode(1);
        TreeNode node4 = new TreeNode(3);
        TreeNode node5 = new TreeNode(6);
        TreeNode node6 = new TreeNode(9);
        root.left = node1;
        root.right = node2;
        node1.left = node3;
        node1.right = node4;
        node2.left = node5;
        node2.right = node6;

        Create c = new Create();
        c.invertTree(root);
        c.order(root);


    }
}

class Create {
    public void order(TreeNode node) {
        if (node == null) {
            return;
        }
        order(node.left);
        System.out.print(node.val + " ");
        order(node.right);
    }

    /**反转二叉树
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        //向左右递归
        TreeNode l = invertTree(root.left);
        TreeNode r = invertTree(root.right);
        //交换当前根节点的左右子树
        root.left = r;
        root.right = l;
        //root为当前根节点
        return root;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }
}

上一篇:一键保存网页为PDF


下一篇:零基础java自学流程-Java语言高级226