力扣 814题 二叉树剪枝
Question 814-binary tree pruning
解题思路
利用后序遍历,自上而下地执行修建操作:
- 如果当前节点为叶子节点(没有子节点),那么判断它的值是否为 0,如果是,将其修剪掉,如果不是,留着它。
- 如当前节点非叶子节点,那么留着它。
代码
class Solution {
public TreeNode pruneTree(TreeNode root) {
if (null == root) return root;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if (root.left == null && root.right == null) {
if (0 == root.val) {
return null;
} else {
return root;
}
}
return root;
}
}