翻轉一棵二叉樹。
示例:
輸入:
4
/ \
2 7
/ \ / \
1 3 6 9
輸出:
4
/ \
7 2
/ \ / \
9 6 3 1
思路:有關樹的問題要想到遞歸,遞歸的想法很簡單,將根的左右子樹互換之後,再已左右子樹爲根繼續互換。遞歸最重要的就是終止條件,如果傳入的是空指針,或者葉節點,那麼不需要再遞歸了,直接返回根節點。需要注意的是,在子樹遞歸的時候是不需要建立什麼接收遞歸的參數的,不接收返回值程序是沒有問題的。
C++代碼如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return NULL;
TreeNode* tmp=root->left;
root->left=root->right;
root->right=tmp;
invertTree(root->left);
invertTree(root->right);
return root;
}
};