美文网首页
二叉树与图

二叉树与图

作者: 编程半岛 | 来源:发表于2018-08-24 15:43 被阅读52次

    二叉树深度搜索

    1. 路径总和 II

    前序操作和后序操作结合:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            vector<vector<int>> result;
            vector<int> path;
            int path_value = 0;
            pathSum(root, path_value, sum, path, result);
            return result;
        }
        
        void pathSum(TreeNode* node, int& path_value, int sum, vector<int>& path, vector<vector<int>>& result)
        {
            if( !node )
            {
                return ;
            }
            
            path_value += node->val;        //  前序遍历的操作
            path.push_back(node->val);
            
            if( (!node->left) && (!node->right) && (path_value == sum) )
            {
                result.push_back(path);
            }
            
            pathSum(node->left, path_value, sum, path, result);
            pathSum(node->right, path_value, sum, path, result);
            
            path_value -= node->val;        // 后序遍历的操作
            path.pop_back();
        }
    };
    

    2.二叉树的最近公共祖先

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            TreeNode* result = NULL;
            vector<TreeNode*> path;                 // 临时路径
            vector<TreeNode*> p_path;               // 获取走向p的路径
            vector<TreeNode*> q_path;               // 获取走向q的路径
            bool flag = false;                      // 标记是否找到需要查找到结点
            
            pathWay(root, p, path, p_path, flag);   // 获取p_path
            path.clear();                           // 清除path,为查找q的路径做准备
            flag = false;
            pathWay(root, q, path, q_path, flag);   // 获取q_path
            int len = (p_path.size() <= q_path.size()) ? p_path.size() : q_path.size();
            for(int i = 0; i < len; ++i)
            {
                if( p_path[i] == q_path[i] )
                {
                    result = p_path[i];
                }
            }
            
            return result;
        }
        
        void pathWay(TreeNode* node, TreeNode* search_node, vector<TreeNode*>& path, vector<TreeNode*>& search_path , bool& flag)
        {
            if( !node || flag )
            {
                return ;
            }
            
            path.push_back(node);
            if( search_node == node )
            {
                search_path = path;
                flag = true;
            }
            
            pathWay(node->left, search_node, path, search_path, flag);
            pathWay(node->right, search_node, path, search_path, flag);
            path.pop_back();        
        }
    };
    

    3. 二叉树展开为链表

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void flatten(TreeNode* root) {
            TreeNode* last = NULL;
            preorder(root, last);
            return ;
        }
        
        void preorder(TreeNode* node, TreeNode*& last)
        {
            if( !node )
            {
                return ;
            }
            
            if( !node->left && !node->right )       // 如果为叶子节点
            {
                last = node;
                return ;
            }
            
            TreeNode* left_node = node->left;
            TreeNode* right_node = node->right;
            TreeNode* left_last = NULL;
            TreeNode* right_last = NULL;
            
            if( left_node )
            {
                preorder(left_node, left_last);
                node->left = NULL;
                node->right = left_node;
                last = left_last;
            }
            
            if( right_node )
            {
                preorder(right_node, right_last);
                if( left_last )
                {
                    left_last->right = right_node;
                }
                
                last = right_last;
            }
            
        }
    };
    

    二叉树层次遍历

    4.二叉树的右视图

    方法一:通过循环来记录层数

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            vector<int> result;
            queue<TreeNode*> q;
            
            if( root )
            {
                q.push(root);
            }
            
            while( !q.empty() )
            {
                int len = q.size();
                for(int i=0; i<len; ++i)
                {
                    TreeNode* node = q.front();
                    q.pop();
                    if( i == (len - 1))
                    {
                        result.push_back(node->val);
                    }
                    
                    if( node->left )
                    {
                        q.push(node->left);
                    }
                    
                    if( node->right )
                    {
                        q.push(node->right);
                    }
                }
            }
            
            return result;
        }
    };
    

    图的深度搜索/广度搜索

    5.课程表

    struct GraphNode    // 图的邻接表数据结构
    {   
        int label;        // 图的顶点值
        vector<GraphNode*> neighbors;   // 相邻结点指针数组
        GraphNode(int x) : label(x){};  // 构造函数
    };
    
    class Solution {
    public:
        bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
            vector<GraphNode*> graph;       // 申请一个有向图
            vector<int> degree;             // 每个顶点的度
            
            for(int i=0; i<numCourses; ++i)
            {
                degree.push_back(0);                    // 初始化每个顶点的度
                graph.push_back(new GraphNode(i));      // 初始化图的顶点
            }
            
            for(int i=0; i<prerequisites.size(); ++i)   // 构造课程先后关系
            {
                GraphNode* begin = graph[prerequisites[i].second];
                GraphNode* end = graph[prerequisites[i].first];
                begin->neighbors.push_back(end);
                degree[prerequisites[i].first]++;
            }
            
            queue<GraphNode*> q;
            for(int i=0; i<numCourses; ++i)             // 遍历图中度为0的顶点
            {
                if( degree[graph[i]->label] == 0 )
                {
                    q.push(graph[i]);
                }
            }
            
            while( !q.empty() )                             // 通过queue来维护图中结点的度数
            {
                GraphNode* node = q.front();
                q.pop();
                for(int i=0; i<node->neighbors.size(); ++i)
                {
                    degree[node->neighbors[i]->label]--;
                    if( degree[node->neighbors[i]->label] == 0 )
                    {
                        q.push(node->neighbors[i]);
                    }
                }
            }
            
            for(int i=0; i<numCourses; ++i)     // 删除图的顶点
            {
                delete graph[i];
            }
            
            for(int i=0; i<numCourses; ++i)     // 遍历degree数组,如果有degree中有大于零的,即代表形成了环
            {
                if( degree[i] >0 )               
                {
                    return false;
                }
            }
            
            return true;
        }
    };
    

    相关文章

      网友评论

          本文标题:二叉树与图

          本文链接:https://www.haomeiwen.com/subject/ghxriftx.html