LeetCode链接:226. 翻转二叉树 解法1 - 递归 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return null; invertTree(root.left); invertTree(root.right); TreeNode tmpNode = root.left; root.left = root.right; root.right = tmpNode; return root; } } 解法2 - 非递归(层序遍历) /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return null; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); TreeNode tmpNode = node.left; node.left = node.right; node.right = tmpNode; } return root; } }