zoukankan      html  css  js  c++  java
  • Same Tree problem on leetcode

    Problem 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.
    Tags: Tree, Depth-first Search
    Class: Easy

    Source Code:

    we can solve this problem using just one line code, like this:

    public boolean isSameTree(TreeNode p, TreeNode q) {
        return p == null || q == null ? p == null && q == null : p.val != q.val ? false : isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
    

    Although the solution is clean, However, it is difficult to read. Don't worry, we can rewrite it to a more understandable form, like this:

    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null || q == null) return p == null && q == null;
        else if (p.val == q.val) return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        else return false;
    }
    

    cnblogs did a bad job on support for Markdown, you can find a more beautiful composing here

  • 相关阅读:
    java基础---13. 匿名对象
    java基础---12. scanner
    java基础---11. API
    Web APIs---2. DOM(1)
    Web APIs---1.概述
    java基础---10. 封装性
    java基础---9. 面向对象
    java基础---8. 数组
    9月1日,随便写点啥
    银川行路随感
  • 原文地址:https://www.cnblogs.com/moqiguzhu/p/moqiguzhu-leetcode-SameTree.html
Copyright © 2011-2022 走看看