Java [Leetcode 226]Invert Binary Tree

时间:2022-07-01 15:05:48

题目描述:

Invert a binary tree.

     4
/ \
2 7
/ \ / \
1 3 6 9

to

     4
/ \
7 2
/ \ / \
9 6 3 1

解题思路:

我只想说递归大法好。

代码如下:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
TreeNode temp = null;
if(root == null)
return null;
else{
temp = invertTree(root.left);
root.left = invertTree(root.right);
root.right = temp;
}
return root;
}
}