Leetcode 226. Invert Binary Tree
Invert a binary tree.
题目大意:
置换一棵二叉树,每个结点的左结点和右结点交换。
解题思路:
二叉树递归,设置中间值实现两值交换。时间复杂度O(n+m),其中n为结点数,m为边数。
代码:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root)
return NULL;
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
return root;
}
};
本文介绍LeetCode226题目的解法,通过递归方式实现二叉树的翻转,即每个节点的左右子树进行交换。代码采用C++实现,详细展示了如何使用临时变量进行值的交换,并递归地处理每个子节点。
314

被折叠的 条评论
为什么被折叠?



