本文主要是介绍【LeetCode刷题-树】-- 129.求根节点到叶节点数字之和,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
129.求根节点到叶节点数字之和
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public int sumNumbers(TreeNode root) {if(root == null){return 0;}Queue<TreeNode> queNode = new LinkedList<TreeNode>();Queue<Integer> queVal = new LinkedList<Integer>();int ans = 0;queNode.offer(root);queVal.offer(root.val);while(!queNode.isEmpty()){TreeNode now = queNode.poll();int tmp = queVal.poll();if(now.left == null && now.right == null){ans += tmp;}if(now.left!=null){queNode.offer(now.left);queVal.offer(tmp * 10 + now.left.val);}if(now.right!=null){queNode.offer(now.right);queVal.offer(tmp * 10 + now.right.val);}}return ans;}
}
这篇关于【LeetCode刷题-树】-- 129.求根节点到叶节点数字之和的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!