LeetCode题解:Invert Binary Tree

Invert a binary tree.


4
/ \
2 7
/ \ / \
1 3 6 9

to


4
/ \
7 2
/ \ / \
9 6 3 1

题意:将二叉树的左右子树互换

解决思路:DFS或BFS

代码:

DFS:

public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }

        final TreeNode left = root.left,
                right = root.right;
        root.left = invertTree(right);
        root.right = invertTree(left);
        return root;
    }

BFS:

public TreeNode invertTree(TreeNode root) {

        if (root == null) {
            return null;
        }

        final Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            final TreeNode node = queue.poll();
            final TreeNode left = node.left;
            node.left = node.right;
            node.right = left;

            if(node.left != null) {
                queue.offer(node.left);
            }
            if(node.right != null) {
                queue.offer(node.right);
            }
        }
        return root;
    }

你可能感兴趣的:(LeetCode)