LeetCode之Binary Tree Pruning(Kotlin)

問題: We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1. Return the same tree where every subtree (of the given tree) not containing a 1 has been removed. (Recall that the subtree of a node X is X, plus every node that is a descendant of X.) Example 1: Input: [1,null,0,0,1] Output: [1,null,0,null,1] Explanation: Only the red nodes satisfy the property "every subtree not containing a 1". The diagram on the right represents the answer. node

這裏寫圖片描述


方法: 二叉樹優先使用遞歸。第一種狀況:左子樹與右子樹都須要裁剪且當前節點值爲0則向上遞歸須要裁剪;第二種狀況:左子樹與右子樹都須要裁剪且當前節點值爲1則裁剪左右子樹中止遞歸須要裁剪;第三種狀況:左子樹與右子樹不是都須要裁剪則裁剪應該裁剪的子樹並中止遞歸須要裁剪。判斷當前節點是否須要裁剪的條件是值爲0或者當前節點爲空。git

具體實現:github

class BinaryTreePruning {
    // Definition for a binary tree node.
    class TreeNode(var `val`: Int = 0) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }

    fun pruneTree(root: TreeNode?): TreeNode? {
        prune(root)
        return root
    }

    private fun prune(root: TreeNode?): Boolean {
        if (root == null) {
            return true
        }
        val leftPrune = prune(root.left)
        val rightPrune = prune(root.right)
        if (leftPrune && rightPrune) {
            if (root.`val` == 0) {
                return true
            } else {
                root.left = null
                root.right = null
                return false
            }
        } else {
            if (leftPrune) {
                root.left = null
            }
            if (rightPrune) {
                root.right = null
            }
            return false
        }
    }
}

fun main(args: Array<String>) {
    //todo 實現測試用例
}
複製代碼

有問題隨時溝通bash

具體代碼實現能夠參考Github測試

相關文章
相關標籤/搜索