[LeetCode练习]226. 翻转二叉树

翻转一棵二叉树。

示例:

输入:

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

输出:

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

思路:1、递归思想,如果存在左右子树,那么就翻转

代码:

public TreeNode invertTree(TreeNode root) {
    if (root == null) {
        return null;
    }
    if (root.right != null || root.left != null) {
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        if (root.right != null) {
            invertTree(root.right);
        }
        if (root.left != null) {
            invertTree(root.left);
        }
    }
    return root;
}

猜你喜欢

转载自blog.csdn.net/lbh199466/article/details/86563037
今日推荐