1. 程式人生 > >JavaScript刷LeetCode -- 814. Binary Tree Pruning【Medium】

JavaScript刷LeetCode -- 814. Binary Tree Pruning【Medium】

一、題目

  We are given the head node root of a binary tree, where additionally every node’s value is either a 0 or a 1.

  Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.

  (Recall that the subtree of a node X is X, plus every node that is a descendant of X.)

二、題目大意

  給定一個二叉樹,如果二叉樹的子樹中不包含1則刪除,返回新的子樹。

三、解題思路

  採用遞迴的方法,在遞迴的過程中,需要判斷當前子樹是保留還是刪除:

  (root.val == 1 || root.left != null || root.right != null) ? root : null

四、程式碼實現

const pruneTree = root => {
  if (!root) {
    return null
  }
  root.left = pruneTree(root.left)
  root.right = pruneTree(root.right)
  return (root.val == 1 || root.left != null || root.right != null) ? root : null
}

  如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。