The substructure of a tree (the sword refers to an offer) recursive __

Source: Internet
Author: User
Tags time limit
Child structure of the tree number of participants: 1611 time limit: 1 seconds space limit: 32768K pass ratio: 18.19% best record: 0 ms|0k (from Mearo) Topic DescriptionEnter two binary tree a,b to determine whether B is a sub structure.

Link: http://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?rp=1&ru=/ta/coding-interviews&qru =/ta/coding-interviews/question-ranking

Train of thought: To determine whether a B, then, first find B's root node in a position, and then start from the node, compare the left and right subtree is equal;

I am not very good at the tree problem, originally want to own a achievements, the result, incredibly wood has output ... Helpless Ah.

My idea is to build the first number of the team, and then pick up, into the stack, ... Each stack node from the team to take the left and right node into the stack, with a linked list;

By the way, after finding the root node of B in a, a recursive decision to exit is a condition where B arrives null, returns True, or the value of a node and the value of the B node are unequal + or a ratio b is first to NULL, returning false, otherwise recursive to the left and right nodes of the node;

/* 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* Proo
        T1, 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); }

};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.