#树#遍历#leetCode404.左子树之和
Posted Sakura
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#树#遍历#leetCode404.左子树之和相关的知识,希望对你有一定的参考价值。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root == null) return 0; Deque<Result> q = new LinkedList<>(); q.push(new Result(root,false)); int sum = 0; while(q.isEmpty()==false) { Result result = q.poll(); TreeNode parent = result.node; if(result.isLeft && parent.left==null && parent.right==null) { sum += parent.val; } if(parent.left!=null) { q.offer(new Result(parent.left,true)); } if(parent.right!=null) { q.offer(new Result(parent.right,false)); } } return sum; } class Result { TreeNode node; boolean isLeft; Result(TreeNode n,boolean a) { node = n; isLeft = a; } } }
以上是关于#树#遍历#leetCode404.左子树之和的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 404 Sum of Left Leaves