LeetCode-Same Tree & Symmetric Tree

女爷i 2022-08-06 15:07 252阅读 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.

一个是判断一棵树是否对称:

iven a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

  1. 1
  2. / \
  3. 2 2
  4. / \ / \
  5. 3 4 4 3

But the following is not:

  1. 1
  2. / \
  3. 2 2
  4. \ \
  5. 3 3

通过这两道题,可以深刻的体会到树本身递归的特性,用递归求解是非常方便的,代码还非常的简洁:

  1. public boolean isSameTree(TreeNode p, TreeNode q) {
  2. if (p == null && q == null) return true;
  3. else if (p == null || q == null) return false;
  4. if (p.val != q.val) return false;
  5. return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
  6. }
  7. public boolean isSymmetric(TreeNode root) {
  8. if (root == null) return true;
  9. return dfs(root.left, root.right);
  10. }
  11. private boolean dfs(TreeNode left, TreeNode right) {
  12. if (left == null && right == null) return true;
  13. else if (left == null || right == null) return false;
  14. if (left.val != right.val) return false;
  15. return dfs(left.left, right.right) && dfs(left.right, right.left);
  16. }

这种解题实在是太美了。。。

发表评论

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

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

相关阅读