2024年7月17日
递归法翻转二叉树
易错:要考虑节点为空的情况,以及写好边界条件。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
return reverse(root);
}
public TreeNode reverse(TreeNode root){
if(root.left==null && root.right!=null){
root.left=root.right;
reverse(root.left);
root.right=null;
return root;
}
if(root.left!=null && root.right==null){
root.right=root.left;
reverse(root.right);
root.left=null;
return root;
}
if(root.left==null && root.right==null){
return root;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
reverse(root.left);
reverse(root.right);
return root;
}
}
标签:right,TreeNode,14,val,随想录,二叉树,null,root,left
From: https://www.cnblogs.com/hailicy/p/18307390