标签:
https://oj.leetcode.com/problems/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.
/** * Definition for binary tree * 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.val == q.val){ return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }else{ return false;
} } }
解题思路:
递归。两个树相等,当且仅当当前节点value相等,并且左右两个子树也都相等。
退出条件:
当前节点为空。
注意点:
搞清楚当前阶段null和left或right为null的区别。
标签:
原文地址:http://www.cnblogs.com/NickyYe/p/4221030.html