二叉樹與圖

weixin_33860722發表於2018-08-24

二叉樹深度搜尋

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;
    }
};

相關文章