一起学算法-226. 翻转二叉树

一、题目

LeetCode-226. 翻转二叉树
链接:https://leetcode-cn.com/problems/invert-binary-tree/

难度:简单
翻转一棵二叉树。

示例:
输入:

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

输出:

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

二、解题思路

从根节点开始,递归地对树进行遍历。
交换每个节点的交换两棵子树的位置,即可完成以root 为根节点的整棵子树的翻转。

三、实现过程

c++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == nullptr) {
            return nullptr;
        }
        TreeNode* left = invertTree(root->left);
        TreeNode* right = invertTree(root->right);
        root->left = right;
        root->right = left;
        return root;
    }
};

PHP

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root
     * @return TreeNode
     */
    function invertTree($root) {
        if($root == null){
            return null;
        }
        $left = $this->invertTree($root->left);
        $right = $this->invertTree($root->right);
        $root->left = $right;
        $root->right = $left;
        return $root;
    }
}

JavaScript

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
        if (root == null) {
            return null;
        }
        let left = invertTree(root.left);
        let right = invertTree(root.right);
        root.left = right;
        root.right = left;
        return root;
};

四、小结

  1. 时间复杂度:O(N),其中 NN 为二叉树节点的数目。
  2. 空间复杂度:O(1)

你可能感兴趣的:(一起学算法-226. 翻转二叉树)