zoukankan      html  css  js  c++  java
  • 1367. 二叉树中的列表 dfs or bfs

    题目:1367. 二叉树中的列表

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

    题意:略

    思路:两种思路太久没有做算法题了。对这类题目不敏感,想当然以为是dp做法,其实就是dfs或者bfs。

    dfs做法:从最开始进行思考。链表第一个数字和二叉树根节点比较是否相等。

    如果相等,那么链表下一个数字分别和二叉树左,右节点比较。

    如果不相等,那么链表第一个数字(注意一定是第一个数字开始,也就是递归到了某个位置,

    如果发现不相等了,要想继续下去,就必须从第一个数字开始。因为如果不是第一个,当前不相等,就意味着和前面的相等断开了。)继续分别和二叉树左,右节点比较。

    如上述递归下去。时间复杂度:链表长度*二叉树节点个数=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做法:

    枚举每一个二叉树节点和链表从第一个开始匹配。

    对每一个给定的二叉树节点和链表从第一个开始匹配。

    用bfs做法寻找连续相等的路径即可。

  • 相关阅读:
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
  • 原文地址:https://www.cnblogs.com/xiaochaoqun/p/12425886.html
Copyright © 2011-2022 走看看