zoukankan      html  css  js  c++  java
  • 814. Binary Tree Pruning

    package LeetCode_814
    
    /**
     * 814. Binary Tree Pruning
     * https://leetcode.com/problems/binary-tree-pruning/description/
     *
     * 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.)
     * */
    class TreeNode(var `val`: Int) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }
    
    class Solution {
        /*
        * solution: recursion,
        * Time complexity: O(n)
        * Space complexity: O(n)
        * */
        fun pruneTree(root: TreeNode?): TreeNode? {
            if (root == null) {
                return root
            }
            root.left = pruneTree(root.left)
            root.right = pruneTree(root.right)
            if (root.`val` == 1 || root.left != null || root.right != null) {
                return root
            } else {
                return null
            }
        }
    
    }
  • 相关阅读:
    HDU 4389 X mod f(x)
    SRM 400(1-250pt, 1-500pt)
    FZU 2113 Jason的特殊爱好
    POJ 3208 Apocalypse Someday
    HDU 4734 F(x)
    HDU 3555 Bomb
    HDU 2089 不要62
    poj2488(A Knight's Journey)
    poj3267(The Cow Lexicon)
    poj2513(Colored Sticks)
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13042355.html
Copyright © 2011-2022 走看看