LeetCode 226. 翻转二叉树
题目链接:https://leetcode-cn.com/problems/invert-binary-tree/
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
我写的:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 struct TreeNode* invertTree(struct TreeNode* root){ 10 if(root==NULL) return root; 11 struct TreeNode *tmp=root->left; 12 root->left=root->right; 13 root->right=tmp; 14 root->left=invertTree(root->left); 15 root->right=invertTree(root->right); 16 return root; 17 }
官方解法:
1 struct TreeNode* invertTree(struct TreeNode* root){ 2 if(root==NULL) return root; 3 struct TreeNode *right = invertTree(root->right); 4 struct TreeNode *left = invertTree(root->left); 5 root->left = right; 6 root->right = left; 7 return root; 8 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步