描述
226. 翻转二叉树 - 力扣(Leetcode)
分析
DFS的前序是最方便的
实现
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 78 79 80 81 82 83 84 85 86 87 88 89
| import java.util.Queue; import java.util.LinkedList;
public class InvertBinaryTree226 { public static void main(String[] args) { TreeNode root = buildTree(new int[]{1,2,3,4,5,6,7}); root = new Solution().invertTree(root); levelOrderTraversal(root);
}
public static TreeNode buildTree(int[] arr) { return buildTreeHelper(arr, 0); }
public static TreeNode buildTreeHelper(int[] arr, int index) { if (index >= arr.length) { return null; }
TreeNode node = new TreeNode(arr[index]);
node.left = buildTreeHelper(arr, 2 * index + 1); node.right = buildTreeHelper(arr, 2 * index + 2);
return node; }
public static void levelOrderTraversal(TreeNode root) { if (root == null) { return; }
Queue<TreeNode> queue = new LinkedList<>(); queue.add(root);
while (!queue.isEmpty()) { TreeNode node = queue.poll(); System.out.print(node.val + " ");
if (node.left != null) { queue.add(node.left); }
if (node.right != null) { queue.add(node.right); } } } }
class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return root; } invert(root); invert(root.left); invert(root.right);
return root; } void invert(TreeNode root){ TreeNode temp = root.left; root.left = root.right; root.right = temp; } }
class TreeNode { int val; TreeNode left; TreeNode right;
public TreeNode(){}; public TreeNode(int val){this.val = val;} public TreeNode(int val, TreeNode left, TreeNode right){ this.val = val; this.left = left; this.right = right; } }
|
总结