letecode [100] - Same Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true
Example 2:
Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false
Example 3:
Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false
题目大意:
给定两个二叉树判断他们是否相同,若它们结构和节点值均相同,则二叉树相同。
理解:
若根节点均为空,则当前子树相同。不同时为空,则不同。
若当前节点的值相同,则当前节点相同,访问它们的左右子树。
代码C++:
/** * 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; else if((p==NULL&&q!=NULL)||(p!=NULL&&q==NULL)){ return false; } if(p->val==q->val){ return isSameTree(p->left,q->left) && isSameTree(p->right,q->right); } return false; } };
运行结果:
执行用时 : 4 ms 内存消耗 : 9.8 MB