LeetCode oj 226. Invert Binary Tree (DFS||BFS)

226. Invert Binary Tree

 
 My Submissions
  • Total Accepted: 124813
  • Total Submissions: 257083
  • Difficulty: Easy

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
Trivia:
This problem was inspired by this original tweet by Max Howell:
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.
二叉樹的翻轉
做了幾道關於這方面的題,感覺自己已經成爲了一名合格的司機,例行提供DFS或BFS的兩種題解
DFS:
/**
 * 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 temp = root.left;
        root.left = root.right;
        root.right = temp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}
BFS:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        if(root == null)
            return null;
        q.clear();
        q.add(root);
        while(!q.isEmpty()){
            TreeNode temp_root = q.poll();
            TreeNode temp_left = temp_root.left;
            temp_root.left = temp_root.right;
            temp_root.right = temp_left;
            if(temp_root.left != null) 
                q.add(temp_root.left);
            if(temp_root.right != null) 
                q.add(temp_root.right); 
        }
        return root;
    }
}


發佈了244 篇原創文章 · 獲贊 18 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章