814. 二叉树剪枝

痛定思痛。 2023-10-05 21:10 328阅读 0赞

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

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

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

  1. 示例1:
  2. 输入: [1,null,0,0,1]
  3. 输出: [1,null,0,null,1]
  4. 解释:
  5. 只有红色节点满足条件“所有不包含 1 的子树”。
  6. 右图为返回的答案。
  7. 示例2:
  8. 输入: [1,0,1,0,0,0,1]
  9. 输出: [1,null,1,null,1]
  10. 示例3:
  11. 输入: [1,1,0,1,1,0,1,0]
  12. 输出: [1,1,0,1,1,null,1]

说明:

  • 给定的二叉树最多有 100 个节点。
  • 每个节点的值只会为 01

    package Solution814;

    class Solution {

    1. public TreeNode pruneTree(TreeNode root) {
    2. if (root == null) {
    3. return null;
    4. }
    5. root.left = pruneTree(root.left);
    6. root.right = pruneTree(root.right);
    7. if (root.left == null && root.right == null && root.val == 0) {
    8. return null;
    9. }
    10. return root;
    11. }
    12. static void inorder(TreeNode node) {
    13. if (node == null)
    14. return;
    15. /* first recur on left child */
    16. inorder(node.left);
    17. /* then print the data of node */
    18. System.out.printf("%d ", node.val);
    19. /* now recur on right child */
    20. inorder(node.right);
    21. }
    22. public static void main(String[] args) {
    23. Solution sol = new Solution();
    24. // Add nodes to the binary tree
    25. TreeNode root = new TreeNode(1);
    26. // root.left = new TreeNode(2);
    27. root.right = new TreeNode(0);
    28. root.right.left = new TreeNode(0);
    29. root.right.right = new TreeNode(1);
    30. inorder(root);
    31. sol.pruneTree(root);
    32. System.out.println();
    33. inorder(root);
    34. }

    }

发表评论

表情:
评论列表 (有 0 条评论,328人围观)

还没有评论,来说两句吧...

相关阅读

    相关 814. 剪枝

    给定二叉树根结点 `root` ,此外树的每个结点的值要么是 0,要么是 1。 返回移除了所有不包含 1 的子树的原二叉树。 ( 节点 X 的子树为 X 本身,以及所有 X