首页 > 学院 > 开发设计 > 正文

leetcode_404. Sum of Left Leaves

2019-11-06 06:17:51
字体:
来源:转载
供稿:网友

查找二叉树所有左叶子的和。

法1:

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

法2:

public int sumOfLeftLeaves(TreeNode root) { if(root == null) return 0; int ans = 0; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.empty()) { TreeNode node = stack.pop(); if(node.left != null) { if (node.left.left == null && node.left.right == null) ans += node.left.val; else stack.push(node.left); } if(node.right != null) { if (node.right.left != null || node.right.right != null) stack.push(node.right); } } return ans;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表