1. 程式人生 > >LeetCode-226.Invert Binary Tree

LeetCode-226.Invert Binary Tree

class != NPU rtt output input ava inpu pty

Invert a binary tree.

Example:

Input:

     4
   /     2     7
 / \   / 1   3 6   9

Output:

     4
   /     7     2
 / \   / 9   6 3   1
public TreeNode invertTree(TreeNode root) {//樹 遞歸 my
        if (null!=root){
            TreeNode left = invertTree(root.left);
            TreeNode right = invertTree(root.right);
            root.left=right;
            root.right=left;
        }
        return root;
    }  

非遞歸的方法

public TreeNode invertTree(TreeNode root) {
    if (root == null) return null;
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
    while (!queue.isEmpty()) {
        TreeNode current = queue.poll();
        TreeNode temp = current.left;
        current.left = current.right;
        current.right = temp;
        if (current.left != null) queue.add(current.left);
        if (current.right != null) queue.add(current.right);
    }
    return root;
}

  

  

LeetCode-226.Invert Binary Tree