leetcode-pp / 91alg-5-daily-check

91 天学算法第五期打卡
55 stars 14 forks source link

【Day 79 】2021-11-27 - 814 二叉树剪枝 #98

Open azl397985856 opened 2 years ago

azl397985856 commented 2 years ago

814 二叉树剪枝

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/binary-tree-pruning

前置知识

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

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

示例1: 输入: [1,null,0,0,1] 输出: [1,null,0,null,1]

示例2: 输入: [1,0,1,0,0,0,1] 输出: [1,null,1,null,1]

示例3: 输入: [1,1,0,1,1,0,1,0] 输出: [1,1,0,1,1,null,1]

说明:

给定的二叉树最多有 100 个节点。 每个节点的值只会为 0 或 1

yanglr commented 2 years ago

思路

二叉树相关的问题, 很多可以用递归解决。本题也不例外。

方法: dfs(递归)

实现一个dfs函数, 用于判断以结点root为根结点的树是否包含1。

如果dfs(root) == false, 直接返回 NULL; 否则进行返回root。

具体细节见代码~

代码

实现语言: C++

class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if (dfs(root) == false) return nullptr;
        return root;
    }
    bool dfs(TreeNode* root) /* dfs: 以结点root为根结点的树是否包含1 */
    {
        if (root == nullptr) return false;
        if (dfs(root->left) == false) root->left = nullptr;   // 对左子树剪枝: 移除不含值为1的子树
        if (dfs(root->right) == false) root->right = nullptr; // 对右子树剪枝: 移除不含值为1的子树
        /* 如果恰好只剩下根结点, root的值必须为1时以它为根结点的子树才包含1; 如果剪枝完成后还剩下某个子树, 那该子树必然含值为1的结点。 */
        return root->val == 1 || (root->left != nullptr) || (root->right != nullptr);
    }
};

复杂度分析

zhangzz2015 commented 2 years ago

关键点

代码

C++ Code:


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {

        bool hasOne; 

        return dfs(root, hasOne); 

    }

    TreeNode* dfs(TreeNode* root, bool& hasOne)
    {
        if(root == NULL)
        {
            hasOne = false; 
            return NULL; 
        }
        bool leftHasOne = false; 
        bool rightHasOne = false; 
        root->left = dfs(root->left, leftHasOne);
        root->right = dfs(root->right, rightHasOne); 

        hasOne = leftHasOne|| rightHasOne || root->val ==1; 
        if(hasOne==false)
            return NULL; 
        else
            return root; 

    }
};
chaggle commented 2 years ago
title: "Day 79 814. 二叉树剪枝"
date: 2021-11-27T00:10:45+08:00
tags: ["Leetcode", "c++", "tree", "recursion"]
categories: ["91-day-algorithm"]
draft: true

814. 二叉树剪枝

题目

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

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

节点 node 的子树为 node 本身加上所有 node 的后代。

示例 1:

输入:root = [1,null,0,0,1]
输出:[1,null,0,null,1]
解释:
只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。
示例 2:

输入:root = [1,0,1,0,0,0,1]
输出:[1,null,1,null,1]
示例 3:

输入:root = [1,1,0,1,1,0,1,0]
输出:[1,1,0,1,1,null,1]

提示:

树中节点的数目在范围 [1, 200] 内
Node.val 为 0 或 1

题目思路

  • 1、二叉树递归问题
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int dfs(TreeNode* root) {
        if(!root) return 0;
        auto l = dfs(root -> left);
        auto r = dfs(root -> right);
        if(!l) root -> left = nullptr;
        if(!r) root -> right = nullptr;
        return root -> val + l + r;
    }
    TreeNode* pruneTree(TreeNode* root) {
        return dfs(root) != 0 ? root : nullptr;
    }
};

复杂度

ZacheryCao commented 2 years ago

Idea:

DFS

Code:

def dfs(root):
            if not root:
                return None
            else:
                l = dfs(root.left)
                r = dfs(root.right)
                if not l:
                    root.left = None
                if not r:
                    root.right = None
                return l or r or root.val
        return root if dfs(root) else None

Compelxity:

Time: O(N) Space: O(N)

pophy commented 2 years ago

思路

Java Code

    public TreeNode pruneTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        if (root.left == null && root.right == null && root.val == 0) {
            return null;
        } 
        return root;
    }

时间&空间

yingliucreates commented 2 years ago

link:

https://leetcode.com/problems/binary-tree-pruning/

代码 Javascript

const pruneTree = root => {
  if (!root) return null;
  [root.left, root.right] = [pruneTree(root.left), pruneTree(root.right)];
  return (root.val === 1 || root.left || root.right) ? root : null
}
kidexp commented 2 years ago

thoughts

DFS 从下往上遍历

code

class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def dfs(node):
            if not node:
                return None
            node.left, node.right = dfs(node.left), dfs(node.right)
            if node.left or node.right:
                return node
            else:
                return node if node.val == 1 else None

        return dfs(root)

complexity

Time O(n)

Space O(h)

itsjacob commented 2 years ago

Intuition

Implementation

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
  TreeNode *pruneTree(TreeNode *root)
  {
    // post-order DFS binary tree traversal

    // reach the child of the leaf node
    if (root == nullptr) return nullptr;
    // reassign the pruned left subtree
    root->left = pruneTree(root->left);
    // reassign the pruned right subtree
    root->right = pruneTree(root->right);
    // a pruned left/right subtree should be nullptr if there're no 1's in them
    // if i have all zero left/right subtrees and I'm 0 as well, I can tell my parent to assign me as nullptr
    return (root->val == 0 && root->left == nullptr && root->right == nullptr) ? nullptr : root;
  }
};

Complexity

wangzehan123 commented 2 years ago

Java Code:


/**
 * 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 (root==null){
            return null;
        }
        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        return root.val == 0 && root.left == null && root.right==null ? null : root;
    }

}
JiangyanLiNEU commented 2 years ago
var pruneTree = function(root) {
    let dummy = new TreeNode(0, root);
    var dfs = tree => {
        if ( tree === null){
            return true;
        }else{
            if (dfs(tree.left)){
                tree.left = null;
            };
            if (dfs(tree.right)){
                tree.right = null;
            };
            if (tree.right === null && tree.left === null && tree.val == 0){
                return true;
            }else{
                return false;
            }
        }
    };
    dfs(dummy);
    return dummy.left;
}
class Solution(object):
    def pruneTree(self, root):
        def dfs(tree):
            if tree == None:
                return
            if dfs(tree.left):
                tree.left = None
            if dfs(tree.right):
                tree.right = None
            if tree.left==None and tree.right==None and tree.val == 0:
                return True
            else:
                return False
        dummy = TreeNode(0, root)
        dfs(dummy)
        return dummy.left
biancaone commented 2 years ago
class Solution:
    def pruneTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        root.left = self.pruneTree(root.left)
        root.right = self.pruneTree(root.right)

        if root.left or root.right or root.val == 1:
            return root
        return None
falconruo commented 2 years ago

思路: DFS + Recursion

复杂度分析: 方法一、DFS

代码(C++):

方法一、DFS + Recursion
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if (!root) return nullptr;

        root->left = pruneTree(root->left);
        root->right = pruneTree(root->right);

        if (!root->left && !root->right && root->val == 0)
            root = nullptr;

        return root;
    }
};
CoreJa commented 2 years ago

思路

回溯,递归并判断需要剪枝的部分。

代码

    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        root.left = self.pruneTree(root.left)
        root.right = self.pruneTree(root.right)
        if root.left or root.right or root.val == 1:
            return root
        return None
zjsuper commented 2 years ago

DFS + recursion Time (N)

class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def if_1(r):
            if not r:
                return False
            l = if_1(r.left)
            right = if_1(r.right)
            if not l:
                r.left = None
            if not right:
                r.right = None
            if not l and not right and not r.val:
                return None
            else:
                return r
        return if_1(root)
yachtcoder commented 2 years ago
class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        dummy = TreeNode(left=root)
        def remove(node):
            if not node: return False
            l = remove(node.left)
            r = remove(node.right)
            if not l: node.left = None
            if not r: node.right = None
            return node.val == 1 or l or r
        remove(dummy)
        return dummy.left
erik7777777 commented 2 years ago
public TreeNode pruneTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        if (root.left == null && root.right == null) {
            if (root.val == 0) {
                return null;
            }
            return root;
        }
        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        if (root.left == null && root.right == null) {
            return root.val == 0 ? null : root;
        }
        return root;
    }
skinnyh commented 2 years ago

Note

Solution

class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root: return None
        root.left = self.pruneTree(root.left)
        root.right = self.pruneTree(root.right)
        if root.left or root.right or root.val == 1:
            return root
        return None

Time complexity: O(N)

Space complexity: O(H)

yan0327 commented 2 years ago

递归剪枝

func pruneTree(root *TreeNode) *TreeNode {
    if root == nil {
        return nil
    }
    var dfs func(root *TreeNode) (*TreeNode)
    dfs = func(root *TreeNode) (*TreeNode) {
        if root == nil{
            return nil
        }
        root.Left = dfs(root.Left)
        root.Right= dfs(root.Right)
        if root.Left == nil && root.Right == nil && root.Val == 0{
            return nil
        }
        return root
    }
    root = dfs(root)
    return root
}

时间复杂度O(N) 空间复杂度O(H)

jocelinLX commented 2 years ago

思路:利用深度便利法查找节点和左子节点以及 右子节点,若均为0,则令为None。若有一个存在,也就是为1,则保留:

代码使用了郁郁雨的代码
class Solution:

​    def pruneTree(self, root: TreeNode) -> TreeNode:

​        def dfs(node):

​            if not node:

​                return False

​            if not dfs(node.left):

​                node.left=None

​            if not dfs(node.right):

​                node.right=None

​            return node.val==1 or node.left or node.right

​        if dfs(root):

​            return root

​        else:

​            return None
ZJP1483469269 commented 2 years ago

代码

class Solution {
    public TreeNode pruneTree(TreeNode root) {
        TreeNode node = root;
        if(!dfs(node)) return null;
        node.left = pruneTree(node.left);
        node.right = pruneTree(node.right);
        return node;
    }
    public boolean dfs(TreeNode node){
        if(node == null) return false; 
        if(node.val == 1) return true;
        return dfs(node.left) || dfs(node.right);
    }
}
florenzliu commented 2 years ago

Explanation

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def helper(node):
            if not node:
                return False

            left_has_one = helper(node.left)
            right_has_one = helper(node.right)

            if not left_has_one:
                node.left = None
            if not right_has_one:
                node.right = None

            return node.val or node.left or node.right

        return root if helper(root) else None

Complexity

ghost commented 2 years ago

题目

  1. Binary Tree Pruning

思路

DFS

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:

        if not root: return root

        root.left = self.pruneTree(root.left)
        root.right = self.pruneTree(root.right)

        if not root.left and not root.right and root.val == 0:
            return None

        return root

复杂度

Space: O(height) Time: O(n)

pan-qin commented 2 years ago

Idea:

DFS. Do post-order traversal on the tree. Prune its left, then prune its right, if the resulting root has only one node with value of zero, delete this root.

Complexity:

Time: O(n) n is the number of nodes. Space: O(height)

class Solution {
    public TreeNode pruneTree(TreeNode root) {
        if(root==null)
            return null;
        root.left=pruneTree(root.left);
        root.right = pruneTree(root.right);
        if(root.left == null && root.right == null && root.val != 1)
            return null;
        return root;
    }    
}
muimi commented 2 years ago

思路

递归

代码

class Solution {
  public TreeNode pruneTree(TreeNode root) {
    if (root == null) return null;
    root.left = pruneTree(root.left);
    root.right = pruneTree(root.right);
    if (root.left == null && root.right == null && root.val == 0) return null;
    return root;
  }
}

复杂度

weichuliao commented 2 years ago
class Solution(object):
    def pruneTree(self, root):
        def containsOne(node):
            if not node: return False
            left = containsOne(node.left)
            right = containsOne(node.right)
            if not left: node.left = None
            if not right: node.right = None
            return node.val == 1 or left or right

        return root if containsOne(root) else None
shixinlovey1314 commented 2 years ago

Title:814. Binary Tree Pruning.md

Question Reference LeetCode

Solution

Recursivly check on the children, if the subtrees only contains 0, they would be removed, so after checked the subtrees, if this node has no child and its value is 0, we remove this node.

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if (!root)
            return NULL;

        root->left = pruneTree(root->left);
        root->right = pruneTree(root->right);

        if (!root->left && !root->right && root->val == 0)
            return NULL;

        return root;
    }
};

Complexity

Time Complexity and Explanation

O(n) We visit each node exactly once

Space Complexity and Explanation

O(1)

joeytor commented 2 years ago

思路

使用深度优先搜索, 递归的思路

使用递归的方法, 每次返回 这个节点的 1 的个数

递归的 base case 是如果是空节点, 那么返回 0

然后递归查找 左右子树

如果左右子树返回为 0, 代表没有 1, 那么将左右子树断开

然后返回这个节点的 1 的个数, 等于 左子树 1 的个数 + 右子树 1 的个数 + 本身是否为 1

最后返回 root 如果 root 为根的树包含 1, 否则返回 None

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:

        def traverse(node):
            if not node:
                return 0

            left_count = traverse(node.left)
            right_count = traverse(node.right)

            if left_count == 0:
                node.left = None
            if right_count == 0:
                node.right = None

            return left_count + right_count + (1 if node.val == 1 else 0)

        val = traverse(root)
        if val == 0:
            return None
        else:
            return root

复杂度

时间复杂度: O(n) n 为节点个数, 每个节点访问一次

空间复杂度: O(h) h 为树的高度, 是递归栈的深度

15691894985 commented 2 years ago

【Day 79】814 二叉树剪枝

https://leetcode-cn.com/problems/binary-tree-pruning

返回移除了所有不包含 1 的子树的原二叉树。等于剪掉全为0的子树

去对根结点的左子树修剪,再对右子树修剪,如果左右子树都被剪没了,那就判断根结点是不是也要被剪掉。

class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def include(node):
            if not node: return False
            left = include(node.left)
            right = include(node.right)
            if not left:
                node.left = None
            if not right:
                node.right = None
            return node.val ==1 or left or right
        return root if include(root) else None

复杂度分析:

tongxw commented 2 years ago

思路

后序计算左右子树的节点和,如果等于0就剪枝。 设置一个哨兵节点,把root挂在哨兵的左子树上,就不用判断剪掉root的情况了。

代码

class Solution {
    public TreeNode pruneTree(TreeNode root) {
        TreeNode dummy = new TreeNode(-1);
        dummy.left = root;
        dfs(dummy);
        return dummy.left;
    }

    private int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int leftSum = dfs(root.left);
        int rightSum = dfs(root.right);
        if (leftSum == 0) {
            root.left = null;
        }
        if (rightSum == 0) {
            root.right = null;
        }

        return root.val + leftSum + rightSum;
    }
}

TC: O(n) SC: O(h)

Francis-xsc commented 2 years ago

思路

递归

代码


class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if(!root){
            return nullptr;
        }
        root->left=pruneTree(root->left);
        root->right=pruneTree(root->right);
        if(root->val==0&&!root->left&&!root->right){
            return nullptr;
        }        
        return root;
    }
};

复杂度分析

thinkfurther commented 2 years ago
class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def containsOne(node):
            if not node:
                return False
            left = containsOne(node.left)
            right = containsOne(node.right)
            if not left:
                node.left = None
            if not right:
                node.right = None
            return node.val == 1 or left or right

        return root if containsOne(root) else None
watermelonDrip commented 2 years ago
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pruneTree(self, root: TreeNode) -> TreeNode:
        def dfs(node):
            if not node:
                return False
            if not dfs(node.left):
                node.left = None
            if not dfs(node.right):
                node.right = None
            return node.val == 1 or node.left or node.right
        return root if dfs(root) else None
liuyangqiQAQ commented 2 years ago
class Solution {
    public TreeNode pruneTree(TreeNode root) {
        //递归调用左子树
        if(root == null) return null;
        return delRight(root) == 0? null : root;
    }

    public int delRight(TreeNode curRoot) {
        if(curRoot.left != null) {
            if(delRight(curRoot.left) == 0) {
                curRoot.left = null;
            }
        }
        if(curRoot.right != null) {
            if(delRight(curRoot.right) == 0) {
                curRoot.right = null;
            }
        }
        if(curRoot.left == null && curRoot.right == null) {
            return curRoot.val;
        }

        return 1;
    }
}
ai2095 commented 2 years ago

814. Binary Tree Pruning

https://leetcode.com/problems/binary-tree-pruning/solution/

Topics

-Tree -Recursion

思路

Recursion

代码 Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return None

        left = self.pruneTree(root.left)
        right = self.pruneTree(root.right)
        root.left = left
        root.right = right

        if left is None and right is None and root.val == 0:
            root = None
            return root
        else:
            return root

复杂度分析

时间复杂度: O(N)
空间复杂度:O(log(N)) , worst O(N)

yibenxiao commented 2 years ago

【Day 79】814 二叉树剪枝

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if(!root){
            return nullptr;
        }
        root->left=pruneTree(root->left);
        root->right=pruneTree(root->right);
        if(root->val==0&&!root->left&&!root->right){
            return nullptr;
        }        
        return root;
    }
};

复杂度

时间复杂度:O(N)

空间复杂度:O(N)

carterrr commented 2 years ago
    public TreeNode pruneTree(TreeNode root) {
        if(root == null) return null;
        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        // 若子树都被剪掉了 自身==0  也要被剪掉
        // 自底向上剪枝  递归剪 因此是dfs后序遍历
        // 这里包括了两种情况  一是 本身无左右节点的  而是 左右节点被剪掉了的
        if(root.left == null && root.right == null && root.val == 0) 
        return null;
        return root;
    }

}java
chenming-cao commented 2 years ago

解题思路

二叉树后序遍历 + 剪枝。运用递归,先剪左子树,再剪右子树。如果左右子树均被剪掉为null,根也同时为0,那么根也同时剪掉,根设为null,递归结束返回根即可。

代码


class Solution {
    public TreeNode pruneTree(TreeNode root) {
        if (root == null) return null;

        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        if (root.val == 0 && root.left == null && root.right == null) root = null;
        return root;
    }
}

复杂度分析

Daniel-Zheng commented 2 years ago

思路

递归。

代码(C++)

class Solution {
public:
    bool dfs(TreeNode* node) {
        if (node == nullptr) return false;
        bool left = dfs(node->left);
        bool right = dfs(node->right);
        if (!left) node->left = NULL;
        if (!right) node->right = NULL;
        return node->val == 1 || left || right;
    }

    TreeNode* pruneTree(TreeNode* root) {
        return dfs(root) ? root : NULL;
    }
};

复杂度分析

asterqian commented 2 years ago

思路

剪枝,注意使用后序遍历。理由是从叶子节点开始一个个往上删(相当于一圈圈删),如果不是后序遍历的话会漏删一开始在树中间但其实应该删的节点,因为他们一开始就执行过判断。

代码

class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if (!root) return nullptr;
        root->left = pruneTree(root->left);
        root->right = pruneTree(root->right);
        if (!root->left && !root->right && root->val == 0) return nullptr;
        return root;
    }
};
时间复杂度 O(n)
空间复杂度 O(height)
chen445 commented 2 years ago

代码

class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def recursion(node):
            if not node:
                return True
            right=recursion(node.right)
            left=recursion(node.left)
            if right:
                node.right =None
            if left:
                node.left=None
            if right and left and node.val==0:
                return True
            else:
                return False
        if recursion(root): 
            return None
        else:
            return root

复杂度

Time: O(n)

Space: O(n)

jiahui-z commented 2 years ago

思路: dfs

/**
 * 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 (root == null) return null;
        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        if (root.left == null && root.right == null && root.val == 0) return null;
        return root;
    }
}

Time Complexity: O(n), n is the total number of nodes Space Complexity: O(h), h is the height of the tree

AruSeito commented 2 years ago
var pruneTree = function (root) {

    const postTraverse = (root) => {
        if (!root) return null;

        root.left = postTraverse(root.left);
        root.right = postTraverse(root.right);

        return (!root.left && !root.right && root.val === 0) ? null : root;
    };

    return postTraverse(root);
};
ginnydyy commented 2 years ago

Problem

https://leetcode.com/problems/binary-tree-pruning/

Note

Solution

/**
 * 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(root == null){
            return root;
        }

        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);

        if(root.left == null && root.right == null && root.val == 0){
            return null;
        }
        return root;
    }
}

Complexity

learning-go123 commented 2 years ago

思路

代码

Go Code:

func pruneTree(root *TreeNode) *TreeNode {
    if root == nil {
        return nil
    }
    root.Left = pruneTree(root.Left)
    root.Right = pruneTree(root.Right)
    if root.Left == nil && root.Right == nil && root.Val == 0 {
        return nil
    }
    return root
}

复杂度分析

令 n 为数组长度。

kennyxcao commented 2 years ago

814. Binary Tree Pruning

Intuition

Code

/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
const pruneTree = function(root) {
  if (!root) return null;
  root.left = pruneTree(root.left);
  root.right = pruneTree(root.right);
  return (!root.left && !root.right && root.val === 0) ? null : root;
};

Complexity Analysis

huzizailushang commented 2 years ago

class Solution { public: TreeNode pruneTree(TreeNode root) { if (root == nullptr) { return nullptr; } root->left = pruneTree(root->left); // 左子树剪枝,得到剪枝后左子树 root->right = pruneTree(root->right); // 右子树剪枝,得到剪枝后右子树 //关键点:一个节点只有当它的值为0,且它的左右子树值都为空时才需要把它删除(剪枝) if (root->left == nullptr && root->right == nullptr && root->val == 0) { return nullptr; }
return root; // 返回root这棵树剪枝后的结果 } }; 时间复杂度:O(N),其中 NN 是树中节点的个数。 空间复杂度:O(H),其中 HH 是树的高度,为我们在递归时使用的栈空间大小。

xinhaoyi commented 2 years ago

class Solution { public TreeNode pruneTree(TreeNode root) { if (root == null) return null; //这里要注意,当前节点可能不是叶子节点,但如果他的子节点 //都删除完了,它就变成了叶子节点。 //剪枝左子树 root.left = pruneTree(root.left); //剪枝右子树 root.right = pruneTree(root.right); //如果叶子节点的值是0,就把他给删除,返回一个空的节点 if (root.left == null && root.right == null && root.val == 0) return null; //否则不要删除,直接返回即可 return root; } }

Bingbinxu commented 2 years ago

方法 dfs遍历 针对左右和根节点递归 代码

实现语言: C++
class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if (dfs(root) == false) return nullptr;
        return root;
    }
    bool dfs(TreeNode* root) /* dfs: 以结点root为根结点的树是否包含1 */
    {
        if (root == nullptr) return false;
        if (dfs(root->left) == false)
            root->left = nullptr;  
        if (dfs(root->right) == false) 
            root->right = nullptr; 
        return root->val == 1 || (root->left != nullptr) || (root->right != nullptr);
    }
};

复杂度分析 时间复杂度: O(N) 空间复杂度: O(N)

shawncvv commented 2 years ago

思路

递归

代码

JavaScript Code

var pruneTree = function (root) {
  function dfs(root) {
    if (!root) return 0;
    const l = dfs(root.left);
    const r = dfs(root.right);
    if (l == 0) root.left = null;
    if (r == 0) root.right = null;
    return root.val + l + r;
  }
  ans = new TreeNode(-1);
  ans.left = root;
  dfs(ans);
  return ans.left;
};

复杂度

RonghuanYou commented 2 years ago
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return

        root.left = self.pruneTree(root.left)
        root.right = self.pruneTree(root.right)
        if root.val == 0 and not root.left and not root.right:
            return
        return root