Leetcode:226.翻转二叉树

Leetcode:226.翻转二叉树

题目描述

翻转一棵二叉树。

示例:

输入:

 4

/
2 7
/ \ /
1 3 6 9
输出:

 4

/
7 2
/ \ /
9 6 3 1

备注:
这个问题是受到 Max Howell 的 原问题 启发的 :

谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:
本题的思路就是递归,实现起来比较简单,也没有很多特殊情况需要考虑。
从顶上开始往下走,每次交换两个子树即可。

/**
 * 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) return NULL;

		//交换两个子树
        TreeNode* p = root->left; root->left = root->right; root->right = p;

		//通过递归交换下面一层的子树
        root->left = invertTree(root->left);
        root->right = invertTree(root->right);
        
        return root;
    }
};

你可能感兴趣的:(数据结构刷题,#,Leetcode,二叉树,网络,leetcode,算法,manjaro)