Same Tree--比较两个二叉树是否相同
/** * Definition for binary tree * 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) { // Note: The Solution object is instantiated only once and is reused by each test case. }};
晓东分析:
其实两个二叉树是否相同的判断,看起来还是蛮简单的,若用递归实现的话,就是要左,右节点作为根节点的二叉树是都是相同的,且val也要是相同的即可。
只是需要考虑几个特殊情况,比如左右节点一个是null一个不是这样的情况。
代码实现:
/** * Definition for binary tree * 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) { // Note: The Solution object is instantiated only once and is reused by each test case. if(p == NULL && q == NULL) return true; if(!(p != NULL && q != NULL)) return false; bool left_result = isSameTree(p->left, q->left); bool right_result = isSameTree(p->right, q->right); bool value_result = p->val == q->val; return (left_result == true && right_result == true && value_result == true)? true: false; }};
执行结果:
Runtime: 16 ms
希望大家有更好的算法能够提出来,不甚感谢。
若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·