Lintcode: Equivalent binary tree

Source: Internet
Author: User

equivalent binary tree

Check that two binary trees are equivalent. Equivalence means that first two binary trees must have the same structure, and the number of nodes on each corresponding position is equal.

Sample Example
    1             1   / \           /   2   2   and   2   2 /             /4             4

is two equivalent two-fork tree.

    1             1   / \           /   2   3   and   2   3 /               4                 4

is not equivalent.

Solving

The tree has the same structure and the node values are equal.

Direct recursion

/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/**     * @paramA, B, the root of the binary trees. * @returntrue if they is identical, or false. */     Public Booleanisidentical (TreeNode A, TreeNode b) {//Write Your code here        if(A = =NULL&& b = =NULL){             return true; }            if(A = =NULL&& B! =NULL|| a!=NULL&& b = =NULL|| A.val! =b.val) {             return false; }                  returnIsidentical (A.left, B.left) &&isidentical (A.right, b.right); }}

Lintcode: Equivalent binary tree

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.