LeetCode226-翻转二叉树
LeetCode226-翻转二叉树
前序遍历翻转
| 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; }
|
中序遍历翻转
| public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } invertTree(root.left); TreeNode temp = root.left; root.left = root.right; root.right = temp; invertTree(root.left); return root; }
|
后序遍历翻转
| public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } invertTree(root.left); invertTree(root.right); TreeNode temp = root.left; root.left = root.right; root.right = temp; return root; }
|
层序遍历翻转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 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(); TreeNode temp = node.left; node.left = node.right; node.right = temp; if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } return root; }
|