码迷,mamicode.com
首页 > 其他好文 > 详细

100. Same Tree

时间:2016-12-24 09:28:39      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:ret   return   bool   相等   cti   check   ini   for   function   

【题目】

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.

 

【解题】

思路:

这道题要判断树形一样,在这个基础上val一样。

共有5种树型:

1. node为null

2. node是leave

3. node只有左child

4. node只有右child

5. node有两个children

Base cases:

1和2是base case树形

先判断是不是两个node都为null,如果是,return true;

在判断是不是node一个为null一个不为null,如果是,return false;

如果两个node都是leaves, 判断val是不是相等,等则true,不等则false;

Recursive cases:

3, 4和5是recursive case树形

树形均为3: 判断val相等和左child相等

树形均为4: 判断val相等和右child相等

树形均为5: 判断val相等, 左child相等和右child相等

其他:树形不一样

/**
 * 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) {
        // base case: 
        // two nodes are both null: true
        // one is null and another is not: false
        // both are leaves: check the val of the two nodes
        if (p == null && q == null) {
            return true;
        } else if (p == null || q == null) {
            return false;
        } else if (p.left == null && q.left == null && p.right == null && q.right == null) {
            if (p.val == q.val) {
                return true;
            } else {
                return false;
            }
            
        // recursive case:
        } else if (p.left == null && q.left == null && p.right != null && q.right != null) {
            return p.val == q.val && isSameTree(p.right, q.right);
            
        } else if (p.left != null && q.left != null && p.right == null && q.right == null) {
            return p.val == q.val && isSameTree(p.left, q.left);

        } else if (p.left != null && q.left != null && p.right != null && q.right != null) {
            return (p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right));
            
        } else {
            return false;
        }
    }
}

 

100. Same Tree

标签:ret   return   bool   相等   cti   check   ini   for   function   

原文地址:http://www.cnblogs.com/fqmai/p/6216643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!