[Leetcode] Invert Binary Tree 翻轉二叉樹

Invert Binary Tree

Invert a binary tree.測試

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

tothis

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

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

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.遞歸

原題連接leetcode

遞歸法

複雜度

時間 O(N) 空間 O(N) 遞歸棧空間get

思路

這個難倒Max Howell大神的題也是很是經典的一道測試對二叉樹遍歷理解的題。遞歸的終止條件是當遇到空節點或葉子節點時,再也不交換,直接返回該節點。對於其餘的節點,咱們分別交換它的左子樹和右子樹,而後將交換事後的左子樹賦給右節點,右子樹賦給左節點。代碼給出的是後序遍歷的自下而上的交換,先序遍歷的話就是自上而下的交換。it

代碼

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 || (root.left == null && root.right == null)) return root;
        TreeNode newLeft = invertTree(root.right);
        TreeNode newRight = invertTree(root.left);
        root.left = newLeft;
        root.right = newRight;
        return root;
    }
}

迭代法

複雜度

時間 O(N) 空間 O(1)io

思路

迭代法的思路是BFS或者DFS,這兩種方法均可以實現,實際上也是二叉樹的遍歷。BFS用Queue實現,DFS的話將代碼中的Queue換成Stack。class

代碼

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        if(root!=null) q.offer(root);
        while(!q.isEmpty()){
            TreeNode curr = q.poll();
            TreeNode tmp = curr.right;
            curr.right = curr.left;
            curr.left = tmp;
            if(curr.left!=null) q.offer(curr.left);
            if(curr.right!=null) q.offer(curr.right);
        }
        return root;
    }
}
相關文章
相關標籤/搜索