判斷給定的兩顆樹是否相等。即對應位置的對應值是否都相等。node
同時逐個遍歷,一遇到不相等的就直接返回false。this
二叉樹的遍歷就不細說了。.net
<?php /** * Definition for a binary tree node. * class TreeNode { * public $val = null; * public $left = null; * public $right = null; * function __construct($value) { $this->val = $value; } * } */ class Solution { /** * @param TreeNode $p * @param TreeNode $q * @return Boolean */ function isSameTree($p, $q) { if(is_null($p) && is_null($q)){ return true; } if((is_null($p) && !is_null($q)) || (!is_null($p)&&is_null($q))){ return false; } if($p->val !== $q->val){ return false; } $l = $this->isSameTree($p->left, $q->left); if($l === false){ return false; } $r = $this->isSameTree($p->right, $q->right); if($r === false){ return false; } return true; } }
若以爲本文章對你有用,歡迎用愛發電資助。code