[Leetcode-Tree]Sum of Left Leaves

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;
    }
}
相关文章
相关标签/搜索