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)
    }
    
  • 相关阅读:
    百度点聚合功能,自定义针头功能
    iOS之极光推送
    iOS之短信认证
    iOS FMDB
    iOS 远程推送
    iOS之本地推送(前台模式与后台模式)
    iOS指纹识别
    关于——GCD
    关于——NSThread
    给label text 上色 && 给textfiled placeholder 上色
  • 原文地址:https://www.cnblogs.com/mapoos/p/13296843.html
Copyright © 2011-2022 走看看