GVKun编程网logo

662. Maximum Width of Binary Tree二叉树的最大宽度(二叉树最大宽度算法)

7

在本文中,我们将为您详细介绍662.MaximumWidthofBinaryTree二叉树的最大宽度的相关知识,并且为您解答关于二叉树最大宽度算法的疑问,此外,我们还会提供一些关于104.Maximu

在本文中,我们将为您详细介绍662. Maximum Width of Binary Tree二叉树的最大宽度的相关知识,并且为您解答关于二叉树最大宽度算法的疑问,此外,我们还会提供一些关于104. Maximum Depth of Binary Tree、111. Minimum Depth of Binary Tree 二叉树的最小深度、124. Binary Tree Maximum Path Sum - 二叉树中的最大路径和、124. Binary Tree Maximum Path Sum 二叉树上的最大路径和的有用信息。

本文目录一览:

662. Maximum Width of Binary Tree二叉树的最大宽度(二叉树最大宽度算法)

662. Maximum Width of Binary Tree二叉树的最大宽度(二叉树最大宽度算法)

[抄题]:

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

Example 1:

Input: 

           1
         /   \
        3     2
       / \     \  
      5   3     9 

Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).

Example 2:

Input: 

          1
         /  
        3    
       / \       
      5   3     

Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).

Example 3:

Input: 

          1
         / \
        3   2 
       /        
      5      

Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).

Example 4:

Input: 

          1
         / \
        3   2
       /     \  
      5       9 
     /         \
    6           7
Output: 8
Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

从第三层开始,如果已经满了,就要添加新的index

if (level == list.size()) list.add(index);

 

[思维问题]:

完全没思路,因此需要一些基础知识

[英文数据结构或算法,为什么不用别的数据结构或算法]:

We know that a binary tree can be represented by an array (assume the root begins from the position with index 1 in the array). If the index of a node is i, the indices of its two children are 2*i and 2*i + 1. The idea is to use two arrays (start[] and end[]) to record the the indices of the leftmost node and rightmost node in each level, respectively. For each level of the tree, the width isend[level] - start[level] + 1. Then, we just need to find the maximum width.

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

index的初始值为啥是1?不懂,算了

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

找参数只是结果,重要的是把所需的变量找出来

还是按照起点、过程、终点来写,index的左右分别为 2 * index 和  2 * index + 1,

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int max = 1;
    
    public int widthOfBinaryTree(TreeNode root) {
        //corner case
        if (root == null) return 0;
        
        //initialization
        List<Integer> startOfLevel = new ArrayList<Integer>();
        
        //return
        getWidth(root, 1, 0, startOfLevel);
        return max;
    }
    
    public void getWidth(TreeNode root, int index, int level, List<Integer> list) {
        //return null
        if (root == null) return ;
        
        //add the index to list
        if (list.size() == level)
            list.add(index);
        
        max = Math.max(max, index + 1 - list.get(level));
        
        //divide and conquer in left and right
        getWidth(root.left, 2 * index, level + 1, list);
        getWidth(root.right, 2 * index + 1, level + 1, list);
    }
}
View Code

 

104. Maximum Depth of Binary Tree

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,15,7],

 

return its depth = 3.

 

 

很简单的二叉树题目,直接看代码就ok了。

int maxDepth(struct TreeNode* root) {
    
    if(root==NULL) return 0;
    if(root->left==NULL&&root->right==NULL)
        return 1;
    else if(root->left!=NULL&&root->right==NULL)
        return maxDepth(root->left)+1;
    else if(root->left==NULL&&root->right!=NULL)
        return maxDepth(root->right)+1;
    else
        return _max(maxDepth(root->left)+1,maxDepth(root->right)+1);
    
}

int _max(int a,int b)
{
    if(a>b)
        return a;
    else
        return b;
}

111. Minimum Depth of Binary Tree 二叉树的最小深度

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.


解答:

1.我的答案(递归)

/**
  • * 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 min(TreeNode* root,int num){
  • if(root->left == NULL && root->right == NULL)
  • return num;
  • if(root->left == NULL || root->right == NULL){
  • TreeNode* t = (root->left!=NULL?root->left:root->right);
  • return min(t,num+1);
  • }else{
  • int l = min(root->left, num+1);
  • int r = min(root->right, num+1);
  • return l<r?l:r;
  • }
  • }
  • int minDepth(TreeNode* root) {
  • if(!root)
  • return 0;
  • if(root->left == NULL && root->right==NULL)
  • return 1;
  • return min(root,1);
  • }
  • };


  • 2.别人的答案(递归)

    1. class Solution {
    2. public:
    3. int minDepth(TreeNode* root) {
    4. if(!root)
    5. return 0;
    6. else if (!root->left && root->right)
    7. return 1 + minDepth(root->right);
    8. else if (!root->right && root->left)
    9. return 1 + minDepth(root->left);
    10. else return 1 + min(minDepth(root->left), minDepth(root->right));
    11. }
    12. };

    3.别人的答案(BFS)

    1. int minDepth(TreeNode* root) {
    2. if (root == NULL) return 0;
    3. queue<TreeNode*> Q;
    4. Q.push(root);
    5. int i = 0;
    6. while (!Q.empty()) {
    7. i++;
    8. int k = Q.size();
    9. for (int j=0; j<k; j++) {
    10. TreeNode* rt = Q.front();
    11. if (rt->left) Q.push(rt->left);
    12. if (rt->right) Q.push(rt->right);
    13. Q.pop();
    14. if (rt->left==NULL && rt->right==NULL) return i;
    15. }
    16. }
    17. }


    124. Binary Tree Maximum Path Sum - 二叉树中的最大路径和

    124. Binary Tree Maximum Path Sum - 二叉树中的最大路径和

    1 描述

    给定一个非空二叉树,返回其最大路径和。

    路径 : 一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

    用例

    
    输入: [1,2,3]
    
           1
          / \
         2   3
    
    输出: 6
    输入: [-10,9,20,null,null,15,7]
    
       -10
       / \
      9  20
        /  \
       15   7
    
    输出: 42

    解析

    通过 &max 来记录全局最大值,通过返回ret来记录递归返回的值

    二叉树 abc,a 是根结点(递归中的 root),bc 是左右子结点(代表其递归后的最优解)。
    最大的路径,可能的只有三种路径情况:

        a
       / \
      b   c
    1. b + a + c。
    2. b + a + a父
    3. a + c + a父

    其中情况 1,表示如果不联络父结点的情况,或本身是根结点的情况。
    这种情况是没法递归的,但是结果有可能是全局最大路径和。
    情况 2 和 3,递归时计算 a+b 和 a+c,选择一个更优的方案返回,也就是上面说的递归后的最优解啦。
    另外结点有可能是负值,最大和肯定就要想办法舍弃负值(max(0, x))(max(0,x))。

    但是上面 3 种情况,无论哪种,a 作为联络点,都不能够舍弃。

    暴力枚举法

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    
    int result = -2147483648;
    
    int helper(struct TreeNode* root) {
        if (root == NULL) return 0; 
        int left = helper(root->left);
        int right = helper(root->right);
        int threeNodeSum = root->val + left + right;
        int twoNodeSum = root->val + max(left, right);
        int oneNodeSum = root->val;
        int ret = max(twoNodeSum, oneNodeSum);
        int currentMax = max(ret, threeNodeSum);
        result = max(currentMax, result);
        return ret;
    }
    
    int max(int a, int b) {
        return a > b ? a : b; 
    }
    
    int maxPathSum(struct TreeNode* root){
        result = -2147483648;
        int temp = helper(root);
        return result;
    }

    分析

    #define max(a, b) ((a) > (b) ? (a) : (b))
    
    int maxPath = INT_MIN;
    
    int dfs(struct TreeNode *root) {
        if (root == NULL) {
            return 0;
        }
    
        // 左子树的最大和
        int left = dfs(root->left);
        // 右子树的最大和
        int right = dfs(root->right);
        // 当前节点路径(不需要联系父结点,或本身就已经是根结点而无父节点)的最大值 VS 当前全局最大值
        maxPath = max(left + right + root->val, maxPath);
        // 需要联系父节点,因此只返回子树最大分支
        return max(0, max(left, right) + root->val);
    
    }
    
    int maxPathSum(struct TreeNode *root) {
        // 初始化为最小可能的整数
        maxPath = INT_MIN;
        // 深度优先遍历
        dfs(root);
        return maxPath;
    }

    本文由博客一文多发平台 OpenWrite 发布!

    124. Binary Tree Maximum Path Sum 二叉树上的最大路径和

    124. Binary Tree Maximum Path Sum 二叉树上的最大路径和

    Given a binary tree, find the maximum path sum.

    For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

    For example:
    Given the below binary tree,

    1 / \ 2 3

    Return 6.


    题意:

    求连通的最大路径和

    左右两个节点若由根节点连通,则可以作为一条路径

    ----------------------------------------------------------------

    其实嘛...我们递归的来看...

    如果只是一个节点,那么当然就是这个节点的值了.

    如果这个作为root,那么最长路应该就是..

    F(left) + F(right) + val...当然如果left,或者right<0就不用加了的= =

    我盟从下往上找...

    如果不这个不是root,那么就不能把left和right加起来了...因为只是一条路...

    ----------------------------------------------------------------

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    8. * };
    9. */
    10. class Solution {
    11. private:
    12. int ans; //用全局变量记录最大值
    13. public:
    14. int solve(TreeNode* root){
    15. if(root == NULL) return 0;
    16. int left = solve(root->left); //自底向上来做
    17. int right = solve(root->right);
    18. int val = root->val;
    19. if(left > 0) val += left;
    20. if(right > 0) val += right;
    21. if(val > ans) ans = val;
    22. return max(root->val, max(root->val+ left, root->val + right)); //返回时至少包含root节点值
    23. }
    24. int maxPathSum(TreeNode* root) {
    25. if(root == NULL) return 0;
    26. ans = root->val;
    27. solve(root);
    28. return ans;
    29. }
    30. };


    关于662. Maximum Width of Binary Tree二叉树的最大宽度二叉树最大宽度算法的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于104. Maximum Depth of Binary Tree、111. Minimum Depth of Binary Tree 二叉树的最小深度、124. Binary Tree Maximum Path Sum - 二叉树中的最大路径和、124. Binary Tree Maximum Path Sum 二叉树上的最大路径和的相关信息,请在本站寻找。

    本文标签: