Lintcode---翻转二叉树
翻转一棵二叉树
样例
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
思路:依旧采用递归的思路,判断特殊条件后,先交换根节点的左右孩子,然后再对其左右子树进行递归调用。
代码实现也很简单,一次AC。
/**
* 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;
}
if(root->left==NULL&&root->right==NULL){
return;
}
TreeNode* temp=root->right;
root->right=root->left;
root->left=temp;
if(root->right!=NULL){
invertBinaryTree(root->right);
}
if(root->left!=NULL){
invertBinaryTree(root->left);
}
}
};

浙公网安备 33010602011771号