Sub-structure of the tree
- Number of participants: 1611 time limit: 1 seconds space limit: 32768K
- By scale: 18.19%
- best record: 0 ms|0k (from Mearo)
The topic description Input Two binary tree A, B, to determine whether a is a sub-structure of a.
Links: Http://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?rp=1&ru=/ta/coding-interviews&qru =/ta/coding-interviews/question-ranking
Idea: To determine whether there is b in a, then, first find the root node of B in a position, and then from the node, compare the left and right sub-tree is equal;
I am not very good at the tree problem, originally wanted to make a contribution to the first, the result, incredibly wood has output ... Helpless Ah.
My idea is to first put no number in the queue, and then take the number, into the stack, ... Each node out of the stack from the team to take the left and right nodes into the stack, with the linked list;
By the way, when the root node of B is found in a, the condition of recursion is that b arrives at NULL, returns True, or the value of a node is unequal to the value of the B node + or A is preceded by a null for B, and returns false; otherwise, the left and right nodes of the node are recursive;
/*struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right; TreeNode (int x): Val (x), left (null), right (null) {}};*/class solution{public: bool Hassubtree (treenode* pRoot1, treenode* PRoot2) { bool bo=false; if (pRoot1 && pRoot2) { if (proot1->val==proot2->val) Bo=judgetree (PROOT1,PROOT2); if (!bo) Bo=hassubtree (PROOT1->LEFT,PROOT2); if (!bo) Bo=hassubtree (PROOT1->RIGHT,PROOT2); } return bo; } BOOL Judgetree (TreeNode *p1,treenode *p2) { if (!P2) return true; if (!P1) return false; if (P1->val!=p2->val) return false; Return Judgetree (P1->left,p2->left) && judgetree (p1->right,p2->right); };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The sub-structure of a tree (the offer of a sword) recursion