1315. Sum of Nodes with Even-Valued Grandparent

Link

Solution

DFS思路

  • 推演的過程中要告訴我們什麼?

    • 狀態的更新 (global variable)

      • 最終和

    • 推演的過程需要什麼 (input of dfs)

      • grandpa的值

    • 子問題的答案 (return value)

      • 沒有

        int ret;
          public int sumEvenGrandparent(TreeNode root) {
              dfs(root, 1, 1);
              return ret;
          }
          
          public void dfs(TreeNode node, int p, int gp){
              if(node == null) return;
              if(gp%2 == 0) ret += node.val;
              dfs(node.left, node.val, p);
              dfs(node.right, node.val, p);
          }

Last updated

Was this helpful?