云计算百科
云计算领域专业知识百科平台

(LeetCode 面试经典 150 题) 100. 相同的树 (深度优先搜索dfs)

题目:100. 相同的树

在这里插入图片描述 在这里插入图片描述 思路:深度优先搜索dfs,时间复杂度0(n)。

C++版本:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/

class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==nullptr &&q==nullptr) return true;
if(p==nullptr || q==nullptr) return false;
return p->val==q->val && isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
};

JAVA版本:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/

class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null &&q==null) return true;
if(p==null || q==null) return false;
return p.val==q.val && isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
}

GO版本:

/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/

func isSameTree(p *TreeNode, q *TreeNode) bool {
if p==nil && q==nil {return true}
if p==nil || q==nil {return false}
return p.Val==q.Val && isSameTree(p.Left,q.Left) && isSameTree(p.Right,q.Right)
}

赞(0)
未经允许不得转载:网硕互联帮助中心 » (LeetCode 面试经典 150 题) 100. 相同的树 (深度优先搜索dfs)
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!