Re: [闲聊] 每日LeetCode

楼主: idiont (supertroller)   2023-02-18 11:08:04
226. Invert Binary Tree
给一棵二元树,
要把树上的每个节点的左右子节点都交换。
Example 1:
Input: root = [4, 2, 7, 1, 3, 6, 9]
Output: [4, 7, 2, 9, 6, 3, 1]
Explanation:
https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg
Example 2:
Input: root = [2, 1, 3]
Output: [2, 3, 1]
Explanation:
https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg
Example 3:
Input: root = []
Output: []
Explanation:
树上没有任何节点,直接返回空的树
解题思路:
递回处理左右子节点,
然后把当前节点的左右子节点交换。
C++ code:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return NULL;
TreeNode *temp = root->right;
root->right = invertTree(root->left);
root->left = invertTree(temp);
return root;
}
};
作者: a9486l (a9486l)   2023-02-18 11:25:00
大师
作者: umi0912umi (UMI)   2023-02-18 11:25:00
这礼拜6天有3天都是我写过的= =
作者: Rushia (みけねこ的鼻屎)   2023-02-18 12:06:00
这题很有名Max Howell去面试google写不出这题被刷掉

Links booklink

Contact Us: admin [ a t ] ucptt.com