タイトル説明(中難易度)
オリジナルタイトルリンク
同様の件名:安全プランを証明する|サブツリー(再帰的なC ++)
注:でisSameを使用して、なぜisSameが残って現在のルートと右のサブツリーを決定するためにのみ使用され、すべてのポイントを通過することができない場合ので、間違っています!!!
同時に、良い習慣のテーマを行うために、独自のアルゴリズムを開発
C ++コード
class Solution {
public:
// 1. 遍历二叉树的每个结点p
// 2. 以p为根节点的子树与链表head匹配(都从开头匹配)
// 3. 如果当前点的值不相同,则返回false,否则去判断左子树和右子树能否和链表head->next匹配
// 4. 如果链表遍历到NULL,则表示前面都能匹配,返回true,如果树遍历到NULL,则返回false
bool isSubPath(ListNode* head, TreeNode* root) {
// Read Twice and Up-Down Mode
if (!head) return true;
if (!root) return false;
if (isSame(head, root)) return true;
// Why using isSame is wrong: 因为如果是用isSame只是判断了当前左右子树的根节点,并不能遍历所有的点!!!
return isSubPath(head, root->left) || isSubPath(head, root->right);
}
bool isSame(ListNode* head, TreeNode* root) {
if (head == NULL) return true;
if (root == NULL) return false;
if (root->val != head->val) return false;
return isSame(head->next, root->left) || isSame(head->next, root->right);
}
// If wrong, carefully DEBUG. Read by lines and check the variables name specially!!!
};
ホワイトボードプログラミング
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x)
: val(x)
, left(NULL)
, right(NULL) {
}
};
struct ListNode {
int val;
ListNode *next;
ListNode(int x)
: val(x)
, next(NULL) {
}
};
// create tree by preorder, -1 means NULL
TreeNode *createTree() {
int d;
cin >> d;
if (d == -1) return NULL;
TreeNode *root = new TreeNode(d);
root->left = createTree();
root->right = createTree();
return root;
}
// create linked list, -1 means NULL
ListNode *createList() {
int d;
cin >> d;
if (d == -1) return NULL;
ListNode *head = new ListNode(d);
head->next = createList();
return head;
}
// 1. 遍历二叉树的每个结点p
// 2. 以p为根节点的子树与链表head匹配(都从开头匹配)
// 3. 如果当前点的值不相同,则返回false,否则去判断左子树和右子树能否和链表head->next匹配
// 4. 如果链表遍历到NULL,则表示前面都能匹配,返回true,如果树遍历到NULL,则返回false
bool isSame(ListNode *head, TreeNode *root) {
if (head == NULL) return true;
if (root == NULL) return false;
if (root->val != head->val) return false;
return isSame(head->next, root->left) || isSame(head->next, root->right);
}
bool isSubPath(ListNode *head, TreeNode *root) {
if (!head) return true;
if (!root) return false;
if (isSame(head, root)) return true;
return isSubPath(head, root->left) || isSubPath(head, root->right);
}
int main() {
// Tree: 1 2 -1 -1 3 4 -1 -1 -1
// List: 1 3 -1
TreeNode *root = createTree();
ListNode *head = createList();
if (isSubPath(head, root))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
最後に書かれたブログは思考の知識をまとめたコンピュータサイエンスの分野を中心に、レビューは、私の目標を理解することは容易である各ブログを書くために、:技術と知識を共有することは喜びである、と私はみんなを歓迎します一緒に学習の交換をして、そこにコメントエリアには疑問もありませんが、またあなた(^∀^●)との深い交流を楽しみにすることができます