C语言重构【226】翻转二叉树

it2023-07-09  67

文章目录

所有题目源代码:[Git地址](https://github.com/ch98road/leetcode)题目方案:复杂度计算

所有题目源代码:Git地址

题目

翻转一棵二叉树。 示例: 输入: 4 / \ 2 7 / \ / \ 1 3 6 9 输出: 4 / \ 7 2 / \ / \ 9 6 3 1 备注: 这个问题是受到 Max Howell 的 原问题 启发的 :

方案:

/** * 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 root; invert(root); return root; } void invert(TreeNode* root){ TreeNode* tmp; if(root->left!=NULL||root->right!=NULL) { tmp=root->left; root->left=root->right; root->right=tmp; } if(root->left!=NULL) invert(root->left); if(root->right!=NULL) invert(root->right); } };
复杂度计算
时间复杂度:O(n)空间复杂度:O(1)
最新回复(0)