226.翻转二叉树
力扣题目链接(opens new window)
翻转一棵二叉树。
/**
* 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 void swap(TreeNode root){
TreeNode tempNode;
tempNode = root.left;
root.left = root.right;
root.right = tempNode;
}
public TreeNode invertTree(TreeNode root) {//中序遍历交换左右子树
if(root == null) return root;
swap(root);//根
invertTree(root.left);//左
invertTree(root.right);//右
return root;
}
}