LeetCode 226. Invert Binary Tree
Problem
226. Invert Binary Tree
1. 题目简述
翻转一棵二叉树。例如:
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
2. 算法思路
一道被大佬吐槽的easy题目。DFS或者BFS均可。
DFS
递归调用invert,前中后序均可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return root; }
TreeNode temp = root.left; root.left = root.right; root.right = temp;
if (root.left != null) { root.left = invertTree(root.left); } if (root.right != null) { root.right = invertTree(root.right); }
return root; }
public TreeNode invertTree(TreeNode root) { if (root == null) { return root; }
if (root.left != null) { root.left = invertTree(root.left); }
TreeNode temp = root.left; root.left = root.right; root.right = temp;
if (root.right != null) { root.right = invertTree(root.right); }
return root; } public TreeNode invertTree(TreeNode root) { if (root == null) { return root; }
if (root.left != null) { root.left = invertTree(root.left); } if (root.right != null) { root.right = invertTree(root.right); }
TreeNode temp = root.left; root.left = root.right; root.right = temp;
return root; } }
|
BFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return root; }
Queue<TreeNode> queue = new LinkedList(); queue.add(root);
while (!queue.isEmpty()) { TreeNode node = queue.poll(); TreeNode temp = node.left; node.left = node.right; node.right = temp;
if (node.left != null) { queue.add(node.left); } if (node.right != null) { queue.add(node.right); } }
return root; } }
|