1. 程式人生 > >leetcode-- 100. Same Tree

leetcode-- 100. Same Tree

desc als 邊界 null sam solution all == blank

1、問題描述

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.

2、邊界條件:無

3、思路:遞歸,兩顆數is same的條件是val相等,子樹也是same。但是判斷val的前提條件是有val,即不為null。

base case:兩顆數都為空;一顆為空,一顆不為空。

4、代碼實現

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {//base case是兩個節點都為空
            
return true; } if (p == null || q == null) { return false; } return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } }

leetcode-- 100. Same Tree