LeetCode -- Same Tree
題目描述:
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.
比較兩個二叉樹是否完全相同。
思路:
直接對兩個樹從根節點同時DFS,使用全局成員來記錄是否相等即可。
實現代碼:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public bool IsSameTree(TreeNode p, TreeNode q)
{
CompareTree(p, q);
return _same;
}
private bool _same = true;
private void CompareTree(TreeNode p , TreeNode q)
{
if(!_same){
return;
}
if(p == null && q == null){
return ;
}
if(p == null && q != null || q == null && p != null || p.val != q.val){
_same = false;
return;
}
CompareTree(p.left, q.left);
CompareTree(p.right, q.right);
}
}