题目描述:翻转一棵二叉树
样例:
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
做题思路:用递归遍历左右子树,用swap交换结点的值。
关键代码:
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
// write your code here
if(root==NULL) return;
invertBinaryTree(root->left);
invertBinaryTree(root->right);
swap(root->left,root->right);
}
};做题感想:刚开始没有注意函数返回值为void,判断根结点是否为空的时候,返回的是空,之后改成了return,而且查到了swap函数是改变指针指向地址的值,就用递归交换了左右子树的结点。
本文介绍了一种通过递归实现的翻转二叉树算法。该算法使用C++编写,通过交换每个节点的左右子节点来完成整棵树的翻转。文中详细解释了递归过程及关键代码。
557

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



