226. Invert Binary Tree
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1100. Same Tree
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
解析:二叉树的反转和判断问题,简单的递归问题:
Invert Binary Tree:
/**
* 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 == NULL) return NULL;
invertTree(root->left);
invertTree(root->right);
swap(root->left,root->right);
return root ;
}
};
Same Tree:
/**
* 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:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == NULL && q == NULL) return true ;
if((p!=NULL && q==NULL) || (p==NULL && q!=NULL) || (p->val!=q->val))
return false;
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
};