[LeetCode]Sum Root to Leaf Numbers

来源:互联网 发布:广州数据库培训机构 编辑:程序博客网 时间:2024/06/11 03:18

题目描述

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1   / \  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

一个二叉树的节点值仅为0-9这10个数中的一个,一条由根节点到叶子节点的路径值为根到叶节点的值的顺序排列的10进制数,求所有这些路径值的和。

解题思路


思路很简单,利用栈来按层遍历二叉树,同时用另一个栈来记录每层节点对应的路径值,最终可以求得所有路径值的合。

代码

public static int sumNumbers(TreeNode root) {int result = 0;if (root == null)return result;if (root.left == null && root.right == null)return root.val;Stack<Integer> stackVal = new Stack<Integer>();Stack<TreeNode> stackNode = new Stack<TreeNode>();TreeNode tempNode;int tempVal;stackVal.add(root.val);stackNode.add(root);while (!stackNode.isEmpty()) {tempNode = stackNode.pop();tempVal = stackVal.pop();if (tempNode.left == null && tempNode.right == null) {result += tempVal;} else {if (tempNode.left != null) {stackNode.add(tempNode.left);stackVal.add(tempVal * 10 + tempNode.left.val);}if (tempNode.right != null) {stackNode.add(tempNode.right);stackVal.add(tempVal * 10 + tempNode.right.val);}}}return result;}public static class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}}


0 0
原创粉丝点击