(前序 简单)leetcode 226翻转二叉树

代码随想录说用前序遍历和后序遍历方便,而中序遍历比较绕。

活用自定义函数使程序结构更为清晰

这里用的是前序遍历,根结点root指向left和root,交换root的左右指向

执行过程:

也就是交换下例的 2 ,7

使得交换后,2后面指向的结点跟着到右边去了,7后面指向的左右结点跟着到左边的结点去了。

(突然想到可以做剪枝,遇到叶子结点就直接回溯。)

再交换2 后面的左右结点

7交换后面的左右结点

cpp 复制代码
/**
 * 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) {
        bitree(root);
return root;
    }
    void bitree(TreeNode *root)
    {
        if(root==NULL)
        return ;
        sweap1(root,root->left,root->right);
        bitree(root->left);
        bitree(root->right);
        
        


    }
    void sweap1(TreeNode *root,TreeNode *left,TreeNode *right)
{
    TreeNode *t=new TreeNode;
    t=right;
root->right=root->left;
root->left=t;

}

};
相关推荐
coder777715 分钟前
js逆向分享
javascript·爬虫·python·算法·安全
冠位观测者37 分钟前
【Leetcode 每日一题 - 补卡】1534. 统计好三元组
数据结构·算法·leetcode
明月看潮生42 分钟前
青少年编程与数学 02-016 Python数据结构与算法 25课题、量子算法
python·算法·青少年编程·量子计算·编程与数学
weixin_445054721 小时前
力扣刷题-热题100题-第35题(c++、python)
c++·python·leetcode
JNU freshman1 小时前
C. Robin Hood in Town思考与理解
算法
_x_w2 小时前
【17】数据结构之图及图的存储篇章
数据结构·python·算法·链表·排序算法·图论
anscos2 小时前
Actran声源识别方法连载(二):薄膜模态表面振动识别
人工智能·算法·仿真软件·actran
-优势在我2 小时前
LeetCode之两数之和
算法·leetcode
WaitWaitWait012 小时前
LeetCode每日一题4.17
算法·leetcode
小媛早点睡2 小时前
贪心算法day9(合并区间)
算法·贪心算法