美文网首页
【1错1对0】Sum of Left Leaves

【1错1对0】Sum of Left Leaves

作者: 7ccc099f4608 | 来源:发表于2019-01-21 01:08 被阅读5次

    https://leetcode.com/problems/sum-of-left-leaves/

    日期 是否一次通过 comment
    2019-01-21 01:06 思路太僵
    2019-01-21 01:06 Y
    image.png

    (来源:https://leetcode.com/problems/sum-of-left-leaves/

    关键:preOrder + 识别出left leaf node

    1. 非递归:TODO;
    2. 递归:preOrder,处理好何时加上()

    1. 非递归

    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if(root == null) {
                return 0;
            }
            
            Stack<TreeNode> nodeS = new Stack<>();
            nodeS.push(root);
            
            int leftSum = 0;
            while(!nodeS.isEmpty()) {
                TreeNode node = nodeS.pop();
                if(node.left != null) {
                    if(node.left.left == null && node.left.right == null) {
                        leftSum +=  node.left.val;
                    }
                }
                if(node.right != null) {
                    nodeS.push(node.right);
                }
                if(node.left != null) {
                    nodeS.push(node.left);
                }
            }
            
            return leftSum;
        }
    }
    

    2.递归

    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if(root == null) {
                return 0;
            }
            
            TreeNode nodeSum = new TreeNode(0);
            helper(root, nodeSum);
            
            return nodeSum.val;
        }
        
        private void helper(TreeNode root, TreeNode nodeSum) {
            if(root == null) {
                return;
            }
            
            if(root.left != null) {
                if(root.left.left == null && root.left.right == null) {
                    nodeSum.val += root.left.val;
                }
            }
            
            helper(root.left,nodeSum );
            helper(root.right,nodeSum );
        }
    }

    相关文章

      网友评论

          本文标题:【1错1对0】Sum of Left Leaves

          本文链接:https://www.haomeiwen.com/subject/kykqjqtx.html