zoukankan      html  css  js  c++  java
  • 111. 二叉树的最小深度


    https://www.bilibili.com/video/av46402848/
    考虑的方面要谨慎

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int minDepth(TreeNode root) {
            if(root==null)
    			 return 0;
    		 if(root.left==null)
    			return minDepth(root.right)+1;   //!!!!!关键 左子树为null 就看 右子树
    		if(root.right==null)
    			return minDepth(root.left)+1;    //!!!!!关键 右子树为null 就看 左子树
    		 int left = minDepth(root.left) +1;
    		 int right = minDepth(root.right) +1;
    		 return Math.min(left,right);        //!!!!!关键
        }
    }
    

    用链表实现 层次遍历

    class Solution {
    	public int minDepth(TreeNode root) {
    		int res = 0;
    		if (root == null)
    			return res;
    		LinkedList<TreeNode> ll = new LinkedList<TreeNode>();
    		ll.add(root);
    		while (!ll.isEmpty()) {
    			int size = ll.size();
    			res++; // 要用两个while 的原因主要是增加层作用
    			while (size > 0) {
    				TreeNode temp = ll.poll();
    				if (temp.left == null && temp.right == null)
    					return res;
    				if (temp.right != null)
    					ll.add(temp.right);
    				if (temp.left != null)
    					ll.add(temp.left);
    				size--;
    			}
    		}
    		return res;
     
    	}
    }
    
  • 相关阅读:
    深拷贝与浅拷贝
    ifconfig命令不可用
    多边形裁剪问题
    ps aux命令后的内容
    STL sort的危险之处
    jdk与jre的区别
    #与##的用法
    投影选择的一般原则
    关于函数中内存操作
    js生成新加坡的NRIC号码
  • 原文地址:https://www.cnblogs.com/cznczai/p/11148263.html
Copyright © 2011-2022 走看看