美文网首页算法提高之LeetCode刷题Leetcode
几道有关二叉树 DFS 和 BFS 的算法题

几道有关二叉树 DFS 和 BFS 的算法题

作者: DejavuMoments | 来源:发表于2019-05-23 23:13 被阅读0次

102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]
/**
 * 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> > levelOrder(TreeNode* root) {
        //return BFS(root);
        
        vector<vector<int> > ans;
        DFS(root, 0, ans);
        return ans;
    }
    
private:
    vector<vector<int> > BFS(TreeNode* root){
        // 如果根节点为空,返回空数组
        if(!root) return {};
        
        vector<vector<int> > ans;
        
        vector<TreeNode*> cur, next;
        
        cur.push_back(root);
        
        while(!cur.empty()){
            // C++ 中 vector.back() 返回当前 vector 最末一个元素的引用
            ans.push_back({});
            for(TreeNode* node : cur){
                // C++ 中 vector.back() 返回当前 vector 最末一个元素的引用
                ans.back().push_back(node->val);
                if(node->left) next.push_back(node->left);
                if(node->right) next.push_back(node->right);
            }
            
            cur.swap(next);
            next.clear();
        }
        
        return ans;
    }
    
    void DFS(TreeNode* root, int depth, vector<vector<int>>& ans){
        // 如果根节点为空,那么就直接 return ,不做任何处理
        // if(!root) return;
        if (root == NULL) return;
        
        // works with pre/in/post order
        while(ans.size() <= depth) ans.push_back({});
        
        DFS(root->left, depth+1, ans);
        DFS(root->right, depth+1, ans);
        ans[depth].push_back(root->val); // post-order
    }
};

103. Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]
/**
 * 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>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if(root == nullptr) return ans;
        
        queue<TreeNode*> q{{root}};
        bool left2right = true;
        while(!q.empty()){
            int level = 0;
            vector<int> level_nodes;
            for(int i = 0, n = q.size(); i < n; i++){
                auto node = q.front();
                q.pop();
                if(left2right){
                    level_nodes.push_back(node->val);
                }else{
                    level_nodes.insert(level_nodes.begin(), node->val);
                }
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
            // after this level
            left2right=!left2right;
            ans.push_back(level_nodes);
        }
        return ans;
    }
};

107. Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [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:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> ans;
        if(root == nullptr) return ans;
        
        queue<TreeNode*> q{{root}};
        
        while(!q.empty()){
            
            vector<int> level_nodes;
            
            for(int i = 0, n = q.size(); i < n; i++){
                auto node = q.front();
                
                q.pop();
                
                level_nodes.push_back(node->val);
                
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
            ans.insert(ans.begin(),level_nodes);
        }
        return ans;
    }
};

104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

Solution 1 DFS

/**
 * 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:
    int maxDepth(TreeNode* root) {
        
        if(root == nullptr) return 0;
        
        // 以下两行可以加快速度,从 16ms 到 8ms
        if(!root->left) return 1 + maxDepth(root->right);
        if(!root->right) return 1 + maxDepth(root->left);
        
        return 1 + max(maxDepth(root->right), maxDepth(root->left));
    }
};

Solution 2 BFS
4ms

/**
 * 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:
    int maxDepth(TreeNode* root) {
        
        if(root == nullptr) return 0;
        
        queue<TreeNode*> q{{root}};
        
        int max_depth = 0;
        
        while(!q.empty()){
            max_depth++;
            for(int i = 0, n = q.size(); i < n; i++){
                auto node = q.front();
                q.pop();
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
        }
        return max_depth;
    }
};

111. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

Solution 1 : DFS

/**
 * 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:
    int minDepth(TreeNode* root) {
        
        if(root == nullptr) return 0;
        
        if(root->left == nullptr) return minDepth(root->right) + 1;
        
        if(root->right == nullptr) return minDepth(root->left) + 1;
        
        return 1 + min(minDepth(root->right), minDepth(root->left));
    }
};

Solution 2 : BFS

BFS reaches the minimal depth leaf node before DFS.

class Solution {
public:
    int minDepth(TreeNode* root) {
        
        if(root == nullptr) return 0;
        
        int min_depth = 0;
        
        queue<TreeNode*> q {{root}};
        
        while(!q.empty()){
           
            min_depth++;
            
            for(int i = q.size(); i > 0; i--){
                
                auto node = q.front();
                
                q.pop();
                
                if(!node->left && !node->right) return min_depth;
                
                if(node->left) q.push(node->left);
                
                if(node->right) q.push(node->right);
            }
        }
        return min_depth;
    }
};

513. Find Bottom Left Tree Value

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input:

    2
   / \
  1   3

Output:
1

Example 2:

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

Note: You may assume the tree (i.e., the given root node) is not NULL.

/**
 * 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:
    int findBottomLeftValue(TreeNode* root) {
        int ans = 0;
        if(root == nullptr) return 0;
        
        queue<TreeNode*> q{{root}};
        
        while(!q.empty()){
            
            vector<int> level_nodes;
            
            for(int i = 0, n = q.size(); i < n; i++){
                TreeNode* node = q.front();
                q.pop();
                level_nodes.push_back(node->val);
                if(node->left)  q.push(node->left);
                if(node->right) q.push(node->right);
            }
            ans = level_nodes[0];
        }
        return ans;
    }
};

相关文章

  • 几道有关二叉树 DFS 和 BFS 的算法题

    102. Binary Tree Level Order Traversal Given a binary tre...

  • 神奇的UnionFind (1)

    今天学习了神奇的并查集,UnionFind,试着做了几道之前用BFS/DFS的算法题,感觉超好用! UnionFi...

  • BFS

    [TOC] BFS 和 DFS BFS广度有限搜索和DFS深度优先搜索算法是特别常用的两种算法 DFS 算法就是回...

  • 大一上acm总结

    先说说都学了些什么吧。1 . 三个算法专题,高精度,dfs,bfs,高精度基础应用没什么问题,dfs,bfs,题做...

  • DFS与BFS LeetCode 刷题小结(一)

    本节我们将汇总一些 LeetCode bfs与dfs相关的题。 关于深度优先搜索(DFS)和广度优先搜索(BFS)...

  • BFS和DFS的基本思想

    最近碰到BFS和DFS的编程题比较多,所以想整理一下相关算法的基本思想,以便以后使用。 1.DFS(深度优先搜索)...

  • 图的桥和割点

    内容概要: 图中的桥 图的DFS遍历树和BFS遍历树及其与寻桥算法的关系 图的割点 DFS和BFS的对比小结 桥(...

  • LeetCode 力扣 102. 二叉树的层次遍历

    题目描述(中等难度) 二叉树的层次遍历,输出一个 list 的 list。 解法一 DFS 这道题考的就是 BFS...

  • 算法-二叉树的遍历实现

    简述 二叉树的遍历分 DFS【深度优先遍历】 和 BFS【广度优先遍历】 两类,其中 DFS 又分为前序遍历,中序...

  • (补)第四周算法备忘

    深度优先, DFS 前中后序遍历二叉树 典型题目 岛屿问题 八皇后问题 广度优先, BFS 层级遍历n叉树 典型题...

网友评论

    本文标题:几道有关二叉树 DFS 和 BFS 的算法题

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