1. question: 翻转二叉树(简单)
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree
示例 1:
1 2
| 输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
|
示例 2:
1 2
| 输入:root = [2,1,3] 输出:[2,3,1]
|
示例 3:
2. answers
这道题也是比较简单的,反转二叉树就是将每个节点的左右节点互换,可以采用层序遍历的方法来做。
代码如下所示:
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
| public class Solution_0022 {
public static TreeNode invertTree(TreeNode root) {
if(root == null) { return null; }
Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root);
int length; TreeNode node, temp;
while(!queue.isEmpty()) {
length = queue.size();
while(length > 0) { node = queue.poll();
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); }
length --; } }
return root; }
public static void main(String[] args) {
TreeNode tn1 = new TreeNode(1); TreeNode tn2 = new TreeNode(3); TreeNode tn3 = new TreeNode(2, tn1, tn2);
TreeNode tn4 = new TreeNode(6); TreeNode tn5 = new TreeNode(9); TreeNode tn6 = new TreeNode(7, tn4, tn5);
TreeNode root = new TreeNode(4, tn3, tn6);
TreeNode newRoot = invertTree(root);
List<List<Integer>> result = Solution_0013_03.levelOrder(root); for(List<Integer> i: result) { for(Integer j : i) { System.out.print(j + " "); } System.out.println(); } } }
|
3. 备注
参考力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 (leetcode-cn.com),代码随想录 (programmercarl.com)。