LEETCODE,[leetcode]100.Same Tree

 2023-10-18 阅读 30 评论 0

摘要:題目 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. 解法一 思路 先序遍歷的遞歸 代碼 /*** Definition for a binary

題目

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.

解法一

思路

先序遍歷的遞歸

代碼

/*** 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 && 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);}
}

解法二

思路

用棧或者隊列來實現層次遍歷,一個棧(隊列) 或者 兩個棧(隊列)都可以。如果用一個棧(隊列),那就是兩棵樹同一個位置的節點同時入棧,出棧的時候同時出棧,然后進行對比。以下用一個隊列實現。

代碼

/*** 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) {Deque<TreeNode> queue = new LinkedList<>();queue.addLast(p);queue.addLast(q);while(!queue.isEmpty()){p = queue.removeFirst();q = queue.removeFirst();if(p == null && q == null)continue;else if(p == null || q == null || q.val!=p.val)return false;else {queue.addLast(p.left);queue.addLast(q.left);queue.addLast(p.right);queue.addLast(q.right);}}return true;}
}

LEETCODE?轉載于:https://www.cnblogs.com/shinjia/p/9736638.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/145755.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息