题目如下:
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.
LeetCode-100 Same Tree
给定两个二叉树,让我们判断两棵二叉树是否完全相同。只需按序遍历每一个二叉树节点即可,判断节点的值是否相等,注意递归的返回条件即可。
代码如下:
/** * 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) { return q == null; } if (q == null) { return p == null; } if (p.val != q.val) { return false; } boolean left = isSameTree(p.left, q.left); boolean right = isSameTree(p.right, q.right); return left == true && right == true; } }
时间复杂度和空间复杂度均为O(n)。
- 本文固定链接: https://weiguangli.com/archives/385
- 转载请注明: lwg0452 于 Weiguang的博客 发表
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!