LeetCode 100. Same Tree (C++)
2017-06-26 17:53
363 查看
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.
思路:前序遍历,判断两树对应node要么都为空,要么都不为空。并且对应node的值必须相等。
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p && !q) return true;
if ((!p && q)||(p && !q)) return false;
return ((p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}
};
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
思路:前序遍历,判断两树对应node要么都为空,要么都不为空。并且对应node的值必须相等。
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p && !q) return true;
if ((!p && q)||(p && !q)) return false;
return ((p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}
};
相关文章推荐
- LeetCode 100. Same Tree(C++版)
- Leetcode_binary-tree-level-order-traversal (updated c++ and python version)
- Leetcode_minimum-depth-of-binary-tree (c++ and python version)
- [C++]LeetCode: 93 Binary Search Tree Iterator (经典题,非递归的中序遍历)
- [C++]LeetCode: 106 Convert Sorted List to Binary Search Tree (有序链表转AVL树)
- [C++]LeetCode: 102 Flatten Binary Tree to Linked List (二叉树转前序链表)
- LeetCode 144 — Binary Tree Preorder Traversal(C++ Java Python)
- [Leetcode] 100. Same Tree
- [C++]LeetCode: 38 Construct Binary Tree from Inorder and Postorder Traversal
- 【LeetCode】100. Same Tree (2 solutions)
- leetcode 100. Same Tree
- LeetCode 98 — Validate Binary Search Tree(C++ Java Python)
- Recover Binary Search Tree leetcode c++
- binary tree zigzag level order traversal leetcode c++
- [C++]LeetCode: 48 Binary Tree Inorder Traversal
- Leetcode_binary-tree-zigzag-level-order-traversal (updated c++ and python version)
- leetcode: Same Tree (C++)
- [C++]LeetCode: 30 Minimum Depth of Binary Tree
- [C++]LeetCode: 100 Convert Sorted Array to Binary Search Tree (AVL树)
- [Leetcode] 100. Same Tree