Invert Binary Tree:
Invert a binary tree.
Example:
Solution:
#include <iostream>
using namespace std;
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 == NULL )
return NULL;
invertTree( root->left );
invertTree( root->right );
swap( root->left, root->right );
return root;
}
};
总结:遇到二叉树相关的问题,要想到用递归的思想