【LeetCode】100. Same Tree 解题报告
2018-03-04 13:06
399 查看
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally
identical and the nodes have the same value.
Example1:
Example2:
Example3:
算法思路:该题的解法就是比较树的结构和内容是否一致,可以采用前序遍历,中序遍历,后序遍历。
该题为简单题
Two binary trees are considered the same if they are structurally
identical and the nodes have the same value.
Example1:
Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true
Example2:
Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false
Example3:
Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false
算法思路:该题的解法就是比较树的结构和内容是否一致,可以采用前序遍历,中序遍历,后序遍历。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if(!p&&!q)return true; if(!p||!q)return false; return p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right); } };
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if(p==null&&q==null) return true; if(p==null||q==null) return false; return p.val==q.val&&isSameTree(p.left,q.left)&&isSameTree(p.right,q.right); } }
该题为简单题
相关文章推荐
- [Leetcode] 100. Same Tree 解题报告
- LeetCode 100. Same Tree 解题报告
- [leetcode] 100. Same Tree 解题报告
- 【LeetCode】100. Same Tree 解题报告
- Leetcode 100. Same Tree 验证树是否相同 解题报告
- LeetCode解题报告 100. Same Tree [easy]
- [leetcode]100. Same Tree@Java解题报告
- [Leetcode] 637. Average of Levels in Binary Tree 解题报告
- 【LeetCode】Diameter of Binary Tree 解题报告
- [Leetcode] 108. Convert Sorted Array to Binary Search Tree 解题报告
- LeetCode-Lowest Common Ancestor of a Binary Search Tree-解题报告
- 【LeetCode】226. Invert Binary Tree 解题报告
- 【LeetCode】270.Closest Binary Search Tree Value(Easy)解题报告
- LeetCode: Binary Tree Level Order Traversal 解题报告
- LeetCode解题报告 257. Binary Tree Paths [easy]
- [LeetCode]Binary Search Tree Iterator,解题报告
- [Leetcode] 270. Closest Binary Search Tree Value 解题报告
- Leetcode 98. Validate Binary Search Tree 验证二叉搜索树 解题报告
- LeetCode解题报告 110. Balanced Binary Tree
- LeetCode Convert Sorted List to Binary Search Tree 解题报告