zoukankan      html  css  js  c++  java
  • 100 Same Tree 相同的树

    给定两个二叉树,写一个函数来检查它们是否相同。
    如果两棵树在结构上相同并且节点具有相同的值,则认为它们是相同的。
    示例 1:
    输入 :      1         1
                 /        /
               2   3     2   3
            [1,2,3],   [1,2,3]
    输出: true
    示例 2:
    输入  :    1          1
                 /          
               2             2
            [1,2],     [1,null,2]
    输出: false
    例 3:
    输入 :     1          1
                /          /
               2   1     1   2
            [1,2,1],   [1,1,2]
    输出: false

    详见:https://leetcode.com/problems/same-tree/description/

    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){
                return false;
            }else if(p.val!=q.val){
                return false;
            }else{
                return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
            }
        }
    }
    
  • 相关阅读:
    模板方法模式
    备忘录模式
    观察者模式
    中介者模式
    迭代器模式
    Char型和string型字符串比较整理
    命令模式
    责任链模式
    代理模式
    dokcer 杂谈
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8717910.html
Copyright © 2011-2022 走看看