In 1367. binary tree list dfs or bfs

Title: List of 1367 binary tree.

Links: https://leetcode-cn.com/problems/linked-list-in-binary-tree/

Meaning of the questions: Slightly

Ideas: two ideas for too long have not done the arithmetic problem. Not sensitive to this kind of problem, thought it was taken for granted dp practice, in fact, dfs or bfs.

dfs practice: think from the very beginning. The first list of digital binary tree root and compare for equality.

If they are equal, then a binary digital comparator respectively and left and right lower node list.

If not equal, then the first number in the list (note that the first number must be the beginning, that is recursive to a location,

If it is found not equal, and in order to continue, we must begin from the first number. Because if not the first, the current is not equal, it means that the previous equivalent disconnected. ), Respectively, and continue to compare binary tree left and right node.

As described recursion. Time complexity: the number of binary node list length * 100 * 2500 =

#define P pair<ListNode*,TreeNode*>

class Solution
{
public:
    bool isSet;
    ListNode* FirstHead;
public:
    bool isSubPath(ListNode* head, TreeNode* root)
    {
        if (!isSet) {
            isSet = true;
            FirstHead = head;
        }
        if(head == NULL) {
            return true;
        }
        if(root == NULL) {
            return false;
        }
        bool res = false;
        if (head->val == root->val) {
            res = isSubPath(head->next, root->right)||isSubPath(head->next, root->left);
            if (res) {
                return res;
            }
        }
        if(FirstHead == head) {
            res |= isSubPath(head, root->left)||isSubPath(head, root->right);
        }
        return res;
    }
};

 

bfs practice:

 

Each node of a binary tree enumeration and list beginning with the first match.

For each given node of the binary tree list and starts from the first match.

Looking consecutive equal paths to practice with bfs.

 

Guess you like

Origin www.cnblogs.com/xiaochaoqun/p/12425886.html