问题描述:
翻转一棵二叉树。
示例:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree
解决思路:
1.首先你要明白用递归
2.其次你要明白上层叶子左右交换,从他往下的所以元素连带就交换了,不要想的那么复杂
3.主要理解其递归思想,一通百通
/*
*作者:赵星海
*时间:2020/9/25 9:12
*用途:翻转二叉树
*/
public TreeNode invertTree(TreeNode root) {
if (root==null)return null;
//从上往下递归交换(左右交换)
TreeNode plate = root.left;
root.left = root.right;
root.right = plate;
if (root.left!=null)invertTree(root.left);
if (root.right!=null)invertTree(root.right);
return root;
}
leetCode提交结果: