力扣:226. 翻转二叉树

 递归解题:

1.从头结点开始向下遍历左节点和右节点时,交换中结点的左右节点的值。

2.同时再调用自身的函数来进行各节点的翻转。

/**
 * 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;
        //交换子节点
        TreeNode le = root.left;
        root.left = root.right;
        root.right = le;
        //递归调用
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}

你可能感兴趣的:(树,算法,leetcode)