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.
二叉樹每個結點最多有兩個子結點。 對二叉樹的各種操作要熟悉, 輕松搞定面試中的二叉樹題目一文講得很好。 深搜,簡單的遞歸: (1)如果兩棵樹同時為空,返回真; (2)如果兩棵樹,一棵為空一棵不為空返回假; (3)都不為空時,比較左右子樹,左右子樹都相同則返回真。
/** * 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; } else if (!p || !q) { return false; } if(p->val == q->val) { if(isSameTree(p->left, q->left)&&isSameTree(p->right, q->right)) return true; } return false; }};新聞熱點
疑難解答