Same tree comparisons are the same trees @ Leetcode

Source: Internet
Author: User

Topic:

Given two binary trees, compare whether two binary trees are the same


Ideas:

Recursion.

Base case:

True if both trees are empty trees

If one is empty, false

General

Compare root nodes for equality before recursively comparing left and right subtrees



/**
 * Same Tree
 * 
 * Given binary trees, write a function to check if they is equal or not.
 * 
 * binary trees is considered equal if they is structurally identical and * the nodes has the
 same value.< c6/>* 
 *
/public class S100 {public

	static void Main (string[] args) {
		
	} public
	
	
	Boolean Issametree ( TreeNode p, TreeNode q) {
		//If both are empty, then equal if
        (P==null && q==null) {
        	return true;
        } else if (P==null | | q==null) {	//If an empty one is not empty, the return is not equal to
        	false;
        }
        
        if (P.val = = q.val) {		//If the node values are equal, continue to check the left and right subtree of p,q
        	return Issametree (P.left, Q.left) && Issametree (p.right , q.right);
        } else{
        	return false;}}

}


/**
 * Definition for binary Tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 * *
/public class Solution {public
    boolean issametree (TreeNode p, TreeNode q) {
        if (p==null &&A mp Q==null) {
            return true;
        }
        if (P==null | | q==null) {
            return false;
        }
        if (p.val! = q.val) {
            return false;
        }
        Return Issametree (P.left, Q.left) && issametree (P.right, q.right);
    }
}


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.