Description:
Invert a binary tree.
Example:
Input:
4 / \ 2 7 / \ / \ 1 3 6 9
Output:
4 / \ 7 2 / \ / \ 9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
/**
* 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 = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
这道题应该使用递归的算法不停的交换左右leaf
翻转二叉树算法
本文介绍了一种通过递归算法实现的翻转二叉树方法。该算法通过不断交换二叉树节点的左右子节点来完成整棵树的翻转。示例中展示了输入为特定二叉树时的翻转过程及结果。
303

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



