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 }
原文地址:https://www.cnblogs.com/towerbird/p/11583667.html
时间: 2024-11-09 09:57:51