226. 翻转二叉树
难度简单 774
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
public TreeNode invertTree(TreeNode root) {
if(root==null){
return root;
}
return hepler(root);
}
public TreeNode hepler(TreeNode root) {
if(root==null){
return root;
}
TreeNode left = root.left;
TreeNode right= root.right;
root.left=hepler(right);
root.right=hepler(left);
return root;
}//ok
/**
* 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 root;
}
return hepler(root);
}
public TreeNode hepler(TreeNode root) {
if(root==null){
return root;
}
// TreeNode left = root.left;
// TreeNode right= root.right;
// root.left=hepler(right);
// root.right=hepler(left);
TreeNode left = hepler(root.left);
TreeNode right= hepler(root.right);
root.left = right;
root.right= left;
return root;
}
}