1 public TreeNode pruneTree(TreeNode root) {
2 dfs(root,null,-1);
3 return root;
4 }
5
6 public void dfs(TreeNode cur, TreeNode fa, int left) {
7 if (cur == null) return;
8 if (check(cur)) {
9 if (left == 1) fa.left = null;
10 else fa.right = null;
11 } else {
12 dfs(cur.left, cur, 1);
13 dfs(cur.right, cur, 0);
14 }
15 return;
16 }
17
18 public boolean check(TreeNode node) {
19 if (node == null) return true;
20 if (node.val == 1) return false;
21 return check(node.left) && check(node.right);
22 }
手机扫一扫
移动阅读更方便
你可能感兴趣的文章