Note: This article is available in Chinese only. 本文暂无英文版本。
View original
题意:反转一棵二叉树。。。字面意思理解即可。。就是把每一棵子树的左右孩子交换。。。
思路:直接照着题意做就好了。。。没有坑。。记录的原因是听说这题比较经典(虽然毫无难度…
1/**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10class Solution {
11public:
12
13 bool leaf(TreeNode* root)
14 {
15 if (root->left==NULL&&root->right==NULL) return true;
16 return false;
17 }
18 void dfs(TreeNode* root)
19 {
20 if (leaf(root)) return;
21 TreeNode* tmp = root->left;
22 root->left = root->right;
23 root->right = tmp;
24 if (root->left!=NULL) dfs(root->left);
25 if (root->right!=NULL) dfs(root->right);
26 }
27 TreeNode* invertTree(TreeNode* root) {
28 if (root==NULL) return NULL;
29 dfs(root);
30 return root;
31
32 }
33};