翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
[题源](https://leetcode-cn.com/problems/invert-binary-tree)
二叉树递归套路应用
/**
* 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;
}
if(root.left==null&&root.right==null){
return root;
}
invertTree(root.left);
invertTree(root.right);
TreeNode temp = root.left;
root.left=root.right;
root.right=temp;
return root;
}
}
本文详细介绍了如何使用递归方法实现二叉树的翻转,通过具体示例展示了算法的执行过程,深入理解二叉树节点交换的逻辑。
665

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



