二叉树的镜像
二叉树
题目
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
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
注意:本题与主站 226 题相同:https://leetcode-cn.com/problems/invert-binary-tree/
Related Topics
树
深度优先搜索
广度优先搜索
二叉树
👍 360
👎 0
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
}
}
思路
- 原来输出顺序是中、左、右
- 我们改变输出顺序为中,右、左即可
##实现
class Solution {
public TreeNode mirrorTree(TreeNode root) {
method(root);
return root;
}
private void method(TreeNode node) {
if (node == null) return;
method(node.right);
method(node.left);
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
}
结果
解答成功:
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:39 MB,击败了34.87% 的Java用户