2、问题分析 使用递归 3、代码 1TreeNode* pruneTree(TreeNode*root) {2if(root ==NULL)3returnNULL;4prun(root);5returnroot;6}78voidprun(TreeNode *root)9{10if(root ==NULL)11return;12if(!has_ones(root->left))13root->left =NULL;1415if(!has_ones(root->right))16root->right =NULL;17...
Left != nil || root.Right != nil { return root } // 此时当前子树中的所有子结点都是 0 ,需要修剪掉 return nil } 题目链接: Binary Tree Pruning: leetcode.com/problems/b 二叉树剪枝: leetcode.cn/problems/bi LeetCode 日更第 235 天,感谢阅读至此的你 欢迎点赞、收藏鼓励支持小满...
NULL : root; } }; Github 同步地址: https://github.com/grandyang/leetcode/issues/814 参考资料: https://leetcode.com/problems/binary-tree-pruning/ https://leetcode.com/problems/binary-tree-pruning/discuss/122730/C++JavaPython-Self-Explaining-Solution-and-2-lines LeetCode All in One 题目讲解...
Can you solve this real interview question? Binary Tree Pruning - Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed. A subtree of a node node is node plus every node that is
You should return the following tree:a / \ b c / \ / \ d e f g AnalysisA clever solution exists. Isn't this O(n2), though? It's also a leetcode problem.The in-order traversal gives you an ordering of the elements. You can reconstruct the original binary tree by adding elements...
* TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode pruneTree(TreeNode root) { return containsOne(root) ? root : null; } public boolean containsOne(TreeNode node) { if (node == null) return false;
【LeetCode】二叉树剪枝搜索(Binary Tree Pruning) 原题网址(中):https://leetcode-cn.com/problems/binary-tree-pruning/ 原题网址(英):https://leetcode.com/problems/binary-tree-pruning/ 题目: We are given the head node root of a binary tree, where additionally every node’s value is either ...
Leetcode 814. Binary Tree Pruning dfs 要点是这一句: returnnode.val==1ornode.leftornode.right 完整代码: #Definition for a binary tree node.#class TreeNode:#def __init__(self, x):#self.val = x#self.left = None#self.right = NoneimportfunctoolsclassSolution:...
https://leetcode.com/problems/binary-tree-pruning/description/ 一颗树中有0和1的节点,要求删除所有可以被删除的0节点,直接看下图就明白了。 分析: 如果是叶子节点为0,那直接删除, 删除后 如果新的叶子节点 也是0 继续删除。。。 一开始陷入了如何删除叶子节点的方法上,因此 写了个特别ugly 的code。 定义了...
左右孩子为None22将该结点置为None23"""24classTreeNode:25def__init__(self, x):26self.val =x27self.left =None28self.right =None2930classSolution:31defpruneTree(self, root):32ifroot ==None:33returnNone34root.left =self.pruneTree(root.left)35root.right =self.pruneTree(root.right)36if...