404. Sum of Left Leaves

来源:互联网 发布:yum安装命令 编辑:程序博客网 时间:2024/04/30 17:39

递归方法: 

public int sumOfLeftLeaves(TreeNode root) {

    if(root==null){
             return 0;
         }
    int sum=0;  
    Stack<TreeNode> stacknode= new Stack<>();
    stacknode.push(root);   
    while(!stacknode.isEmpty()){
    root=stacknode.pop();
    if(root.left!=null&&root.left==null&&root.right==null){  //判断左树叶
   
    sum=sum+root.left.val;  
    }
    if(root.left!=null){
    stacknode.push(root.left);
    }
    if(root.right!=null){
    stacknode.push(root.right);
    }
    }
    return sum;

    }

迭代方法

   public int sumOfLeftLeaves(TreeNode root) {
    if(root==null){
             return 0;
         }
    if(root.left!=null&&root.left.left==null&&root.left.right==null){
   
    return root.left.val+sumOfLeftLeaves(root.right);  
    }
    else{
    return sumOfLeftLeaves(root.right)+sumOfLeftLeaves(root.left); 
    }
    }



先写出了迭代的方法,递归还是掌握不熟练,改了好多次。

0 0
原创粉丝点击