100. Same Tree

Difficulty : easy
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.

这道题一开始没想出来,因为tag是DFS, 我以为要写很复杂的recursion,至少是带helper method那种。但看了答案发现题目原本很简单,先比较root的val是不是相等,再比较左右子树isSameTree, 要都为真才能返回true.

/**
 * 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){
            return true;
        }
        if (p == null || q == null){
            return false;
        }
        if (p.val != q.val){
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
    
}

二刷,做到Symmetric Tree的时候回来做的,无压力ac

/**
 * 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){
            return true;
        } else if (p == null || q == null){
            return false;
        }
        if (p.val != q.val){
            return false;
        }
        if (!isSameTree(p.left, q.left)){
            return false;
        }
        if (!isSameTree(p.right, q.right)){
            return false;
        }
        return true;
    }
}

你可能感兴趣的:(100. Same Tree)