leetcode 100. Same Tree 二叉树DFS深度优先遍历

末蓝、 2022-06-08 01:27 272阅读 0赞

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

题意很简单,就是DFS深度优先遍历。

代码如下:

  1. /* class TreeNode
  2. {
  3. int val;
  4. TreeNode left;
  5. TreeNode right;
  6. TreeNode(int x) { val = x; }
  7. }*/
  8. public class Solution
  9. {
  10. public boolean isSameTree(TreeNode p, TreeNode q)
  11. {
  12. return isEqual(p,q);
  13. }
  14. //递归遍历二叉树
  15. private boolean isEqual(TreeNode p, TreeNode q)
  16. {
  17. if(p==null && q==null)
  18. return true;
  19. else if(p==null && q!=null || p!=null && q==null )
  20. return false;
  21. else if(p.val==q.val)
  22. return isEqual(p.left, q.left) && isEqual(p.right, q.right);
  23. else
  24. return false;
  25. }
  26. }

下面是C++的做法,就是做一个DFS深度优先遍历的做法,很简单的

代码如下:

  1. #include<iostream>
  2. #include <vector>
  3. using namespace std;
  4. /*
  5. struct TreeNode
  6. {
  7. int val;
  8. TreeNode *left;
  9. TreeNode *right;
  10. TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  11. };
  12. */
  13. class Solution
  14. {
  15. public:
  16. bool isSameTree(TreeNode* p, TreeNode* q)
  17. {
  18. if (p == NULL && q != NULL || p != NULL && q == NULL)
  19. return false;
  20. else if (p == NULL && q == NULL)
  21. return true;
  22. else if (p->val != q->val)
  23. return false;
  24. else
  25. return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
  26. }
  27. };

发表评论

表情:
评论列表 (有 0 条评论,272人围观)

还没有评论,来说两句吧...

相关阅读