翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
// 根节点为空时直接返回,不为空时交换左右子树,并递归
if (root == null) {
return null;
}
TreeNode temp = null;
temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}

本文详细介绍了如何通过递归算法实现二叉树的翻转,提供了完整的代码示例和解析,帮助读者理解二叉树翻转的基本原理和实现过程。
257

被折叠的 条评论
为什么被折叠?



