100. Same Tree

思路

  1. 全輪尋檢查每個節點都為一致
  2. 如果有一個不同則立即返回 false

實作

public class Solution {
    // 配置節點
    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;
      }
  }

    //傳入樹節點
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true; //7. 剩餘節點比較相同
        if (p != null && q == null) return false;
        if (p == null && q != null) return false;

        //3. 配置預設為相同
        boolean result = true;

        //5. 遇到不同時
        if (p.val != q.val) {
            result = false; // update result
        }else {
            //1. 先設定走過兩樹所有節點(左)
            boolean result_left = isSameTree(p.left, q.left);
            //6. 發現不同時
            if (result_left == false) result = false;
            //2. 先設定走過兩樹所有節點(右)
            boolean result_right = isSameTree(p.right, q.right);
            //6. 發現不同時
            if (result_right == false) result = false;
        }

        //4. 返回結果
        return result;
    }
}