• Minimum -depth -of -binary -tree@LeetCode


    链接:https://www.nowcoder.com/practice/e08819cfdeb34985a8de9c4e6562e724?tpId=46&tqId=29030&tPage=1&rp=1&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking
    来源:牛客网

    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.

    基本思想:

      叶子节点:度0的结点,没有孩子。

      二叉树的最小深度,不同于二叉树的最大深度,不能够单纯使用递归,方式比较所有的叶子节点同时记录所有的到根节点的深度,最后进行比较。

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int run(TreeNode root) {
    12         if (root==null) return 0;
    13         /*使用递归判断此节点是否是叶子节点*/
    14         if(root.left==null && root.right==null) return 1;
    15            /*二叉树左子树空,叶子节点在右子树上*/
    16         if(root.left==null)
    17             return run(root.right)+1;
    18         if(root.right==null)
    19             return 1+run(root.left);
    20         /*左右儿子,比较得到其中最小值*/
    21         return Math.min(run(root.left),run(root.right))+1;
    22     }
    23 }

     C++语言更加的简洁,求最大深度树,将最后11行代码修改成   max(L,R)+1;

     1 class Solution {
     2 public:
     3     int run(TreeNode *root) {
     4         if(root==NULL)
     5             return 0;
     6         int L=run(root->left);
     7         int R=run(root->right);
     8         
     9         if(L==0 || R==0)
    10             return 1+L+R;/*此节点不存在,父节点最多只有一个儿子,计算出叶子叶子节点到此结点的深度,要么只有一个节点,要么根节点*/
    11         return (L<R?L:R)+1;
    12           
    13     }
    14 };
  • 相关阅读:
    Python2-列表
    C#1-变量和表达式
    Python1-变量
    grep输出带有颜色设置
    ftp服务器的安装与使用
    慕课网-哒哒租车系统
    ulimit 命令
    ARP与RARP
    return 和exit
    java运行机制
  • 原文地址:https://www.cnblogs.com/woainifanfan/p/6443810.html
Copyright © 2020-2023  润新知