zoukankan      html  css  js  c++  java
  • Daily Coding Problem: Problem #622

    /**
     * Good morning! Here's your coding interview problem for today.
    This problem was asked by Google. Given the root of a binary tree, return a deepest node.
     * */
    class TreeNode(var value: Int) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }
    
    class Problem_622 {
        /*
        * soluton DFS: 1. find the height of the tree, 2.scan level by level;
        * Time complexity:O(n), Space complexity:O(1)
        * */
        var deepest = 0
    
        fun findDeepest(root: TreeNode?): Int {
            if (root == null) {
                return 0
            }
            val level = getHeight(root)
            findDeepest(root, level)
            return deepest
        }
    
        private fun findDeepest(root: TreeNode?, level: Int) {
            if (root != null) {
                if (level == 1) {
                    deepest = root.value
                } else if (level > 1) {
                    findDeepest(root.left, level - 1)
                    findDeepest(root.right, level - 1)
                }
            }
        }
    
        private fun getHeight(root: TreeNode?): Int {
            if (root == null) {
                return 0
            }
            val leftHeight = getHeight(root.left)
            val rightHeight = getHeight(root.right)
            return Math.max(leftHeight, rightHeight) + 1
        }
    }
  • 相关阅读:
    树莓派开机启动
    树莓派连接18b20测温度
    树莓派VNC
    树莓派python 控制GPIO
    树莓派笔记
    用nohup执行python程序时,print无法输出
    mysql 函数应用
    mysql 正则表达式判断是否数字
    mysql select into 不支持
    tushare
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13456679.html
Copyright © 2011-2022 走看看