leetcode 226. 翻转二叉树

思路:递归得到左右子树,交换左右子树,返回根节点

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == NULL) //递归出口
        {
            return NULL;
        }
        TreeNode *left = invertTree(root->left); //递归得到左子树
        TreeNode *right = invertTree(root->right);//递归得到右子树
        root->left = right; //交换左右子树
        root->right = left;
        return root;
    }
};

 

posted @ 2021-09-26 15:26  A-inspire  Views(22)  Comments(0Edit  收藏  举报