Leetcode Note: Same Tree

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.