226. Invert Binary Tree
- Total Accepted: 124813
- Total Submissions: 257083
- Difficulty: Easy
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
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:BFS:/** * 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; } }
/** * 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; } }