Correct a Binary Tree
给一个二叉树, 其中有一个node是invalid, 这种invalid是他的右子树连到了右边的任意node. 求删除这个错误的子树后的树.
这个题主要是读懂题, 理解这种invalid只能发生在某个node的右子树上. 然后查重要用set. 就没了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
/** * 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 { Set<TreeNode> set = new HashSet<>(); public TreeNode correctBinaryTree(TreeNode root) { if(root == null) return root; if(root.right != null) { if(root.right.right != null && set.contains(root.right.right)) { root.right = null; return root; } else{ set.add(root.right); correctBinaryTree(root.right); } } if(root.left != null) { if(root.left.right != null && set.contains(root.left.right)) { root.left = null; return root; } else{ set.add(root.left); correctBinaryTree(root.left); } } return root; } } |