leetcode404_左葉子之和
阿新 • • 發佈:2022-03-06
題目連結:https://leetcode-cn.com/problems/sum-of-left-leaves/
要讀懂題目,題目要的是左葉子之和,是左葉子不是做節點!
最開始的寫法:
class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root == null) return 0; int ans = 0; if(root.left != null) { if(root.left.left == null && root.left.right == null) ans += root.left.val; ans += sumOfLeftLeaves(root.left); } if(root.right != null) { ans += sumOfLeftLeaves(root.right); } return ans; } }
反思:但凡是樹的遞迴,你必須要想清楚,到底是哪個序列的遍歷?
這裡是後序遍歷(左右中),因為你需要計算出左右子樹的左葉子的節點,然後和本樹的左葉子相加,最後返回。
class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root == null) return 0; int ans = 0; ans += sumOfLeftLeaves(root.left); ans += sumOfLeftLeaves(root.right); if(root.left != null && root.left.left == null && root.left.right == null) ans += root.left.val; return ans; } }
其實可能前序遍歷和後序遍歷差不多吧,比如精簡版的就用的是前序遍歷:
class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root == null) return 0; int midValue = 0; if(root.left != null && root.left.left == null && root.left.right == null) midValue += root.left.val; return midValue + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right); } }