Given binary trees, write a function to check if they is equal or not.
The binary trees is considered equal if they is structurally identical and the nodes has the same value.
Idea one: The idea of pre-order recursion. Time complexity O (n), Spatial complexity O (LOGN)
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: A BOOLIssametree (TreeNode *p, TreeNode *q) { - if(!p &&!q)return true; - if(!p | |!q)return false; the - return(P->val = = q->val) && issametree (P->left, Q->left) && issametree (P->right, q->Right ); - } -};
Idea two: The thought of hierarchical traversal. Time complexity O (n), Spatial complexity O (LOGN)
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: A BOOLIssametree (TreeNode *p, TreeNode *q) { -Queue<treenode *>s; - S.push (p); the S.push (q); - - while(!S.empty ()) { -p =S.front (); + S.pop (); -Q =S.front (); + S.pop (); A if(!p &&!q)Continue; at if(!p | |!q)return false; - if(P->val! = q->val)return false; - -S.push (p->Left ); -S.push (q->Left ); -S.push (p->Right ); inS.push (q->Right ); - } to + return true; - } the};
[Leetcode] Same Tree