Problem
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.
Example 2:
Input: [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]
Example 3:
Input: [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]
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; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/71931.html
Problem Binary Tree PruningWe are given the head node root of a binary tree, where additionally every nodes value is either a 0 or a 1. Return the same tree where every subtree (of the given tree) not...
摘要:题意从一颗二叉树转为带括号的字符串。这题是的姊妹题型,该题目的解法在这里解法。 LeetCode 606. Construct String from Binary Tree You need to construct a string consists of parenthesis and integers from a binary tree with the preorder t...
摘要:题意从一个带括号的字符串,构建一颗二叉树。其中当而时,展示为一个空的括号。同时要考虑负数的情况,所以在取数字的时候,必须注意所在位置。遇到则从栈中出元素。最后中的元素就是,返回栈顶元素即可。 LeetCode 536. Construct Binary Tree from String You need to construct a binary tree from a string ...
摘要:题意判断一颗二叉树是否是平衡二叉树,平衡二叉树的定义为,每个节点的左右子树深度相差小于这是和求最大深度的结合在一起,可以考虑写个函数找到拿到左右子树的深度,然后递归调用函数判断左右子树是否也是平衡的,得到最终的结果。 LeetCode 110 Balanced Binary Tree Given a binary tree, determine if it is height-bala...
摘要:代码解题思路先序遍历,同样用迭代实现,借助栈。先将根节点入栈先序遍历,所以直接出根节点因为顺序是根,左节点,右节点,所以我们在压栈的时候要先压右节点,再压左节点。所以我们自定义了一个类,添加了的属性,来表明该节点是否已经被访问过了。 Binary Tree Inorder TraversalGiven a binary tree, return the inorder traversa...
阅读 1610·2023-04-25 14:12
阅读 1080·2021-08-27 16:24
阅读 2538·2019-08-30 15:44
阅读 2918·2019-08-30 13:16
阅读 1669·2019-08-29 14:10
阅读 970·2019-08-29 13:54
阅读 1301·2019-08-29 13:09
阅读 1810·2019-08-26 18:37