解题思路
按层级来找二叉树的左右两个节点,出口是叶子节点的左右树都是null,找到最后一层的左右两个节点后,对调左右节点,返回节点,而后逐级网上找左右两个节点,再进行对调,再返回节点。
/**
* 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;
}
if (root.left == null && root.right == null) {
return root;
}
TreeNode leftTreeNode = invertTree(root.left);
TreeNode rightTreeNode = invertTree(root.right);
root.right = leftTreeNode;
root.left = rightTreeNode;
return root;
}
}