Invert Binary Tree(leetcode226)

Invert a binary tree.git

Example:github

Input:this

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

Output:code

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

Trivia:
This problem was inspired by this original tweet by Max Howell:遞歸

//使用遞歸的方式
public static TreeNode invertTree(TreeNode root) {
    if (root == null) {
        return null;
    }
    TreeNode right = invertTree(root.right);
    TreeNode left = invertTree(root.left);
    root.left = right;
    root.right = left;
    TreeNode.printMidTreeNode(root.root);
    System.out.println();
    return root;
}

//使用Queue隊列
public TreeNode invertTree2(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;
}

git:https://github.com/woshiyexinjie/leetcode-xin隊列

相關文章
相關標籤/搜索