問題描述:
翻轉一棵二叉樹
樣例
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
解題思路:
運用遞歸方式,將二叉樹的左、右子樹交換
代碼:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
if(root==NULL) return;
else{
invertBinaryTree(root->left);
invertBinaryTree(root->right);
TreeNode*q=root->left;
root->left=root->right;
root->right=q;
}
// write your code here
}
};
感想:
不能直接在遞歸過程中將左、右子樹交換,注意類的返回類型爲空