Leetcode Note: Same Tree
I. Description
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.
Ii. Question Analysis
The meaning of the question is very simple. Determine whether the two sides are the same, recursively, and compare the nodes of the two sides.
Iii. Sample Code
# Include
Using namespace std; 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 and q do not reach the leaf node at the same time, else if (p! = NULL & q = NULL) | (p = NULL & q! = NULL) return false; return (p-> val = q-> val) & isSameTree (p-> left, q-> left) & isSameTree (p-> right, q-> right );}};
Iv. Summary
This is a basic topic in binary tree traversal.