LeetCode.226. 翻转二叉树
难度:easy
BFS和DFS两种方法:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ // DFS class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return root; } TreeNode tmpNode = root.left; root.left = root.right; root.right = tmpNode; invertTree(root.left); invertTree(root.right); return root; } } //BFS class Solution { public TreeNode invertTree(TreeNode root) { List<Double> ansList = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); if (root == null) { return null; } queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode tmpNode = queue.poll(); // 反转左右儿子 TreeNode node = tmpNode.left; tmpNode.left = tmpNode.right; tmpNode.right = node; if (tmpNode.left != null) { queue.offer(tmpNode.left); } if (tmpNode.right != null) { queue.offer(tmpNode.right); } } } return root; } }