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

  • 相关阅读:
    最短路问题之Dijkstra算法
    最短路问题之Bellman-ford算法
    最小生成树之Kruskal(克鲁斯卡尔)算法
    二分图问题
    七桥问题与欧拉道路
    拓扑排序
    八连通块
    四连通检测
    USACO19DEC题解
    1206 雅礼集训D2题解
  • 原文地址:https://www.cnblogs.com/moqiguzhu/p/moqiguzhu-leetcode-SameTree.html
Copyright © 2011-2022 走看看