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.
The two binary trees are identical, that is, the left and right children of a node are equal to the left and right children of the corresponding node of the other tree. Similar to the image symmetric tree.
Code:
/*** 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 theSame (TreeNode * p, TreeNode * q) {if (p = NULL & q = NULL) return true; if (p = NULL | q = NULL) return false; return p-> val = q-> val & theSame (p-> left, q-> left) & theSame (p-> right, q-> right);} bool isSameTree (TreeNode * p , TreeNode * q) {if (p = NULL & q = NULL) return true; if (p! = NULL & q = NULL | p = NULL & q! = NULL) return false; return theSame (p, q );}};
Same Tree (binary Tree DFS)