Lintcode 175 Invert Binary Tree

Lintcode 175 Invert Binary Tree_第1张图片

I did it in a recursive way. There is another iterative way to do it. I will come back at it later.

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
     
    // method 1: recursion
    // 注意交换的是node,不是int value
    public void invertBinaryTree(TreeNode root) {
        if (root == null)
            return;
        
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        
        invertBinaryTree(root.left);
        invertBinaryTree(root.right);
    }
}

 

你可能感兴趣的:(Lintcode 175 Invert Binary Tree)