算法作业_38(2017.6.20第十八周)

来源:互联网 发布:游戏美工培训学费 编辑:程序博客网 时间:2024/05/27 20:51

226. Invert Binary Tree

Invert a binary tree.

     4   /   \  2     7 / \   / \1   3 6   9
to
     4   /   \  7     2 / \   / \9   6 3   1
100. 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);    }};


原创粉丝点击