LeetCode-226~Invert Binary Tree

Invert a binary tree.


Paste_Image.png

to


Paste_Image.png

算法分析

可以使用两种方法实现:递归和迭代。
递归是从最下面的节点开始反转,而迭代是从上面的节点开始。

方法一:递归调用
Java代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        
        root.left = right;
        root.right = left;
        return root;
    }
}
方法二:迭代
java代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        
        Queue queue = new LinkedList();
        queue.add(root);
        while(!queue.isEmpty()) {
            TreeNode current = queue.poll();
            TreeNode temp = current.right;
            current.right = current.left;
            current.left = temp;
            
            if (current.left != null) queue.add(current.left);
            if (current.right != null) queue.add(current.right);
        }
        return root;
    }
}

参考

LeetCode

你可能感兴趣的:(LeetCode-226~Invert Binary Tree)