【Leetcode】NO.226 翻转二叉树(C++&Python)[二叉树]
题目 226. 翻转二叉树
思路
递归方法;
对于每一次使用交换左右节点之后进行递归遍历;
代码
递归方法:
/**
* 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 == NULL)
{
return root;
}
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
层序遍历方法:
本文来自博客园,作者:jucw,转载请注明原文链接:https://www.cnblogs.com/Jucw/p/15769299.html