描述:
翻轉一棵二叉樹
樣例:
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
這個題就是遞歸調用 swap( , ) 函數,交換一個根節點的左右子樹。
代碼:
/**
* 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) {
// write your code here
if(root==NULL)
return;
invertBinaryTree(root->left);
invertBinaryTree(root->right);
swap(root->left,root->right);
}
};