LeetCode Identical Binary Tree 相同二叉树

Love The Way You Lie 2022-06-08 03:17 272阅读 0赞

题目描述:

Check if two binary trees are identical. Identical means the two binary trees have the same structure and every identical position has the same value.

样例输入:

  1. 1 1
  2. / \ / \ 2 2 and 2 2
  3. / /
  4. 4 4
  5. 1 1
  6. / \ / \ 2 3 and 2 3
  7. / \ 4 4

样例输出:

  1. true
  2. false

解法一:

有树的地方就有递归

  1. private boolean isIdenticalRecursion(TreeNode a, TreeNode b) {
  2. if (a == null && b == null) {
  3. return true;
  4. }
  5. if ((a == null && b != null) || (a != null && b == null) || (a.val != b.val)) {
  6. return false;
  7. }
  8. return isIdenticalRecursion(a.left, b.left) && isIdenticalRecursion(a.right, b.right);
  9. }

解法二:

递归能实现的循环也能实现

  1. private boolean isIdenticalPreOrder(TreeNode a, TreeNode b) {
  2. Stack<TreeNode> stack1 = new Stack<>();
  3. Stack<TreeNode> stack2 = new Stack<>();
  4. stack1.push(a);
  5. stack2.push(b);
  6. while (!stack1.empty() && !stack2.empty()) {
  7. TreeNode tmp1 = stack1.pop();
  8. TreeNode tmp2 = stack2.pop();
  9. if (tmp1.val!=tmp2.val){
  10. return false;
  11. }
  12. if (tmp1.right!=null){
  13. stack1.push(tmp1.right);
  14. }
  15. if (tmp2.right!=null){
  16. stack2.push(tmp2.right);
  17. }
  18. if (stack1.size()!=stack2.size()){
  19. return false;
  20. }
  21. if (tmp1.left!=null){
  22. stack1.push(tmp1.left);
  23. }
  24. if (tmp2.left!=null){
  25. stack2.push(tmp2.left);
  26. }
  27. if (stack1.size()!=stack2.size()){
  28. return false;
  29. }
  30. }
  31. return stack1.size() == stack2.size();
  32. }

发表评论

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

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

相关阅读