zoukankan      html  css  js  c++  java
  • same-tree

    /**
    *
    * @author gentleKay
    * 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.
    *
    * 给定两个二叉树,编写一个函数来检查它们是否相等。
    * 如果两个二叉树的结构相同且节点具有相同的值,则认为它们是相等的。
    */

    /**
     * 
     * @author gentleKay
     * 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.
     * 
     * 给定两个二叉树,编写一个函数来检查它们是否相等。
     * 如果两个二叉树的结构相同且节点具有相同的值,则认为它们是相等的。
     */
    
    public class Main13 {
    	public static void main(String[] args) {
    		TreeNode root1 = new TreeNode(4);
    		root1.left = new TreeNode(2);
    		root1.left.left = new TreeNode(1);
    		root1.left.right  = new TreeNode(3);
    		
    		root1.right = new TreeNode(6);
    		root1.right.left = new TreeNode(5);
    		root1.right.right = new TreeNode(7);
    		root1.right.right.right = new TreeNode(8);
    		
    		TreeNode root2 = new TreeNode(4);
    		root2.left = new TreeNode(2);
    		root2.left.left = new TreeNode(1);
    		root2.left.right  = new TreeNode(3);
    		
    		root2.right = new TreeNode(6);
    		root2.right.left = new TreeNode(5);
    		root2.right.right = new TreeNode(7);
    //		root2.right.right.right = new TreeNode(8);
    		
    //		TreeNode root1 = null;
    //		TreeNode root2 = new TreeNode(1);
    		
    		System.out.println(Main13.isSameTree(root1, root2));
    	}
    	
    	public static class TreeNode {
    		int val;
    		TreeNode left;
    		TreeNode right;
    		TreeNode(int x) { val = x; }
    	}
    	
    	public static boolean isSameTree(TreeNode p, TreeNode q) {
    		if (p == null && q == null) {
    			return true;
    		}
    		if (p == null || q == null) {
    			return false;
    		}
    		if (p.val != q.val) {
    			return false;
    		}
    		return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
        }
    }
    
  • 相关阅读:
    研修班第四次课笔记
    形象革命——穿搭
    对管理者的几点要求
    全链路压测
    项目管理最忌的5件事,千万不要忽视!
    2018年计划小目标(9月)PMP
    NLP是什么
    (深度好文)重构CMDB,避免运维之耻
    《转》我们不得不面对的中年职场危机
    项目管理,让自己更从容
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11250477.html
Copyright © 2011-2022 走看看