zoukankan      html  css  js  c++  java
  • 0100. Same Tree (E)

    Same Tree (E)

    题目

    Given two binary trees, write a function to check if they are the same or not.

    Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

    Example 1:

    Input:     1         1
              /        / 
             2   3     2   3
    
            [1,2,3],   [1,2,3]
    
    Output: true
    

    Example 2:

    Input:     1         1
              /           
             2             2
    
            [1,2],     [1,null,2]
    
    Output: false
    

    Example 3:

    Input:     1         1
              /        / 
             2   1     1   2
    
            [1,2,1],   [1,1,2]
    
    Output: false
    

    题意

    判断两个二叉树是否完全一样。

    思路

    递归比较每一个结点是否相同。


    代码实现

    Java

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            if (p == null && q == null) {
                return true;
            } else if (p == null || q == null || p.val != q.val) {
                return false;
            } else {
                return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
            }
        }
    }
    

    JavaScript

    /**
     * Definition for a binary tree node.
     * function TreeNode(val, left, right) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.left = (left===undefined ? null : left)
     *     this.right = (right===undefined ? null : right)
     * }
     */
    /**
     * @param {TreeNode} p
     * @param {TreeNode} q
     * @return {boolean}
     */
    var isSameTree = function (p, q) {
      if (!p && !q) {
        return true
      } else if (!p || !q || p.val !== q.val) {
        return false
      }
    
      return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
    }
    
  • 相关阅读:
    python笔记——调试和异常处理
    [算法学习] 线段树,树状数组,数堆,笛卡尔树
    【cpp】G++中不支持static_cast?
    【生活感想】不够淡定
    数值线性代数小结
    伪逆
    统计机器学习
    Numerical Methods with MATLAB(1)
    吐槽iOS国际化:关于NSLocalizedString的使用
    iOS 沙盒路径操作:新建/删除文件和文件夹
  • 原文地址:https://www.cnblogs.com/mapoos/p/13296843.html
Copyright © 2011-2022 走看看