From 27f86de1337423e77a11a8d2030d392394820463 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Wed, 31 Oct 2018 21:03:51 +0800 Subject: [PATCH] Create 100. Same Tree.md --- 100. Same Tree.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 100. Same Tree.md diff --git a/100. Same Tree.md b/100. Same Tree.md new file mode 100644 index 0000000..99c94d2 --- /dev/null +++ b/100. Same Tree.md @@ -0,0 +1,19 @@ +# [100. Same Tree](https://leetcode.com/problems/same-tree/description/) +# 思路 +判断两棵树是否完全相同。最简单的思路就是递归算法,两棵树非空树完全相同的充要条件是: +* 根的值相同; +* 且左子树和右子树都是分别完全相同的。 + +当然也可以考虑遍历两棵树直到遇到不相同的节点即可返回false,若同时遍历完则返回true。 + +# C++ +``` C++ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if(p == NULL && q==NULL) return true; // 都是空树 + if(p == NULL || q == NULL || (p -> val != q -> val)) return false; + return isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right); + } +}; +```