Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.node
Example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
1.解題思路code
這個題目其實就是基於先序遍歷,用遞歸和非遞歸思想均可以。
1)非遞歸:
藉助棧,在push節點的時候判斷是不是左葉子節點,若是是就累計進sum中。
2)遞歸:
求全部左葉子節點的和,咱們能夠將其分解爲左子樹的左葉子和+右子樹的左葉子和
遞歸結束條件:找到左葉子節點,就能夠返回該節點的val。遞歸
2.代碼it
1) 非遞歸io
public class Solution { Stack<TreeNode> s=new Stack<TreeNode>(); int sum=0; public int sumOfLeftLeaves(TreeNode root) { if(root==null) return 0; pushLeft(root); while(!s.empty()){ TreeNode node=s.pop(); if(node.right!=null) pushLeft(node.right); } return sum; } private void pushLeft(TreeNode root){ TreeNode node=root; while(node!=null){ s.push(node); //判斷是否爲左葉子節點 if(node.left!=null&&node.left.left==null&&node.left.right==null) sum+=node.left.val; node=node.left; } } }
2)遞歸class
public class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root==null) return 0; int leftsum,rightsum; if(root.left!=null&&root.left.left==null&&root.left.right==null) leftsum=root.left.val; else leftsum=sumOfLeftLeaves(root.left); rightsum=sumOfLeftLeaves(root.right); return leftsum+rightsum; } }