LeetCode-Easy刷题(19) Same Tree
Posted 当以乐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-Easy刷题(19) Same Tree相关的知识,希望对你有一定的参考价值。
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
判断两个树是否相同,结构和数值都相同则为相同的树
//树的遍历 结束条件
public 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);
class TreeNode
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) val = x;
以上是关于LeetCode-Easy刷题(19) Same Tree的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode-Easy刷题(31) Single Number