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

  • 相关阅读:
    分页存储过程
    调存储过程
    winform httplicent调用API
    存储过程,触发器,等等。。。
    C# AJAXform上传图片
    Mysql order by与limit联用出现的问题
    将Sublime Text 3 放到右键中
    Vue-cli构建步骤
    Javascript面试知识点
    position详解
  • 原文地址:https://www.cnblogs.com/moqiguzhu/p/moqiguzhu-leetcode-SameTree.html
Copyright © 2011-2022 走看看