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);
        }
    }
    
  • 相关阅读:
    VUE学习笔记--模板渲染
    VUE学习笔记--生命周期 Vue
    VUE学习笔记--实例及选项
    VUE学习笔记--Vue的模板语法
    Vue学习笔记--Vue 简述
    吴裕雄--天生自然--SPRING BOOT--解决:Lifecycle mapping "org.eclipse.m2e.jdt.JarLifecycleMapping" is not available. To enable full functionality, install the lifecycle
    【Vue2.x】Vue UI中无法安装指定版本依赖解决方法
    mysql加锁过程
    java实现交替打印的四种方法
    23th CSP 游记
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11250477.html
Copyright © 2011-2022 走看看