about 2 years ago

Question

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.

這到題目要我們判斷兩個Tree是否相同。

Resolve

這題的解法我們需要依序去判斷兩個tree是否為空,優先判斷若是空值就先回傳true or false,後者在判斷val值是否正確,因此這提示不困難的,但鄙人目前只會土法煉鋼,程式碼大概如下。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        
        if(p == null && q == null) {
            return true;
        }
        
        if(p == null && q != null || p != null && q == null) {
            return false;
        }
        
        if(p.val != q.val) return false;
        
        boolean res = isSameTree(p.left, q.left);
        
        if(!res) return false;
        
        res = isSameTree(p.right, q.right);
        
        if(!res) return false;
        
        return true;
       
    }
}
← [LeetCode] Ugly Number [Spring MVC] CH 1. Hello Spring (IOC、DI) →
 
comments powered by Disqus