博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Same Tree 判断两颗树是否相等
阅读量:4184 次
发布时间:2019-05-26

本文共 875 字,大约阅读时间需要 2 分钟。

题目:

给定两颗二叉树,写一个函数判断这两棵树是否相等。如果两棵树的结构和各节点中保存的值是相等的,则认为这两棵树相等。

思路:

采用先序遍历的方法,从上到下递归考察各节点。

在任意一对节点的比较中,如果左右枝是否为空的属性和节点中的val值不相等,则认为两棵树不是同一棵树,否则继续考察。如果遍历结束后仍然不能证明这两棵树不是同一棵树,则这两棵树就是相等的

实现代码如下:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {
/** * 判断两个树是否为相等 * @param p 树p * @param q 树q * @return */ public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) { return true; } else if ( (p == null && q != null) || (p != null && q == null) || p.val != q.val || !isSameTree(p.left, q.left) || !isSameTree(p.right, q.right)) { return false; } else { return true; } }}

转载地址:http://fxuoi.baihongyu.com/

你可能感兴趣的文章
CareerCup Pots of gold game:看谁拿的钱多
查看>>
CarreerCup Sort Height
查看>>
CareerCup Sort an array in a special way
查看>>
CareerCup Find lexicographic minimum in a circular array 循环数组字典序
查看>>
CareerCup Cost of cutting wood
查看>>
Find the number of subsets such that the sum of numbers in the subset is a prime number
查看>>
CareerCup Binary Tree the Maximum of 人
查看>>
CareerCup Divide n cakes to k different people
查看>>
CareerCup Randomly return a node in a binary tree
查看>>
CareerCup Given a sorted array which contains scores. Write a program to find occurrence
查看>>
CareerCup The number of pairs (x, y) of distinct elements with condition x + y <= Threshold
查看>>
Build a key-value data structure which can perform lookup and rangeLookup(key1, key2)
查看>>
整数划分问题---动态规划、递归
查看>>
Balanced Partition
查看>>
Number of 1s
查看>>
CareerCup Find all the conflicting appointments from a given list of n appointments.
查看>>
CareerCup Given an array having positive integers, find a subarray which adds to a given number
查看>>
CareerCup Generate all the possible substrings
查看>>
CareerCup Given an array A[], find (i, j) such that A[i] < A[j] and (j - i) is maximum.
查看>>
Brain Teaser 球变色
查看>>