二叉树的镜像
题目:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
0 <= 节点个数 <= 1000
节点:
遍历左右节点并交换左右节点:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public TreeNode mirrorTree(TreeNode root) { 12 if(root == null){ 13 return null; 14 } 15 TreeNode left = root.left; 16 TreeNode right = root.right; 17 root.left = right; 18 root.right = left; 19 mirrorTree(left); 20 mirrorTree(right); 21 return root; 22 } 23 }

浙公网安备 33010602011771号