zoukankan      html  css  js  c++  java
  • 814. 二叉树剪枝

    给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。

    返回移除了所有不包含 1 的子树的原二叉树。

    ( 节点 X 的子树为 X 本身,以及所有 X 的后代。)

     

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        public TreeNode pruneTree(TreeNode root) {
            if(containsOne(root))
            {
                return root;
            }
            else
            {
                return null;
            }
            
        }
        public boolean containsOne(TreeNode node)
        {
           if(node == null) return false;
    
           boolean left = containsOne(node.left);
           boolean right = containsOne(node.right);
           if(left == false)
           {
               node.left =null;
           }
           if(right == false)
           {
               node.right = null;
           }
    
           return node.val == 1 || left || right;
    
        }
    }
  • 相关阅读:
    一. js高级(1)-面向对象编程
    tips01- 定位
    h5c3 part6 flex
    h5c3 part5 background and transform
    template and pagination
    h5c3 part4
    h5c3 part3
    h5c3 part2
    h5c3 part1
    学习博客
  • 原文地址:https://www.cnblogs.com/kpwong/p/14690256.html
Copyright © 2011-2022 走看看