兩棵樹是否相同

原題

  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.node

題目大意

  給定兩個二叉樹,判斷這兩棵樹是否相等。
  僅當兩棵樹的結構相同,結點值都相等時都會相等。算法

解題思路

  使用遞歸進行求解,先判斷當前結點值是否相等,若是相等就再比較其左右子樹,只有當全部的結點都相等才相等。ide

代碼實現

樹結點類spa

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

算法實現類.net

public 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 == null && q != null) {
            return false;
        }


        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}
相關文章
相關標籤/搜索