二叉树路径求和

二叉树路径和

给定一棵二叉树,二叉树权值为0-9,得出所有根节点到叶节点的路径和。如下图的二叉树,路径和n=137+15=152


     1  

        /\  

3       5

  \

    7


知道用递归遍历i每条路径:但是具体做法还是请教了我对象,下面是我的代码,还有个句话要说就是这道题和《剑指offer》中的找到路径和为22的路径相似,都是要找出所有路径,这道题见http://blog.youkuaiyun.com/luxiaoxun/article/details/7537605

下面是求每条路径的路径和:

package binayTree;

/**
 * Created by Administrator on 2015/10/30 0030.
 */



import java.util.ArrayList;
import java.util.Stack;

/**
 * Created by chen on 2015/10/30.
 */
class Solution1 {
    ArrayList<String> list1 = new ArrayList<String>();
    Integer sum = 0;
    Stack<Integer> stack=new Stack<Integer>();

    public static void main(String[] args) {
        Solution1 s = new Solution1();
        Stack<Integer> stack=new Stack<Integer>();
        Node root = new Node(1);
        Node node1 = new Node(3);
        Node node2 = new Node(5);
        Node node3 = new Node(7);
        root.left = node1;
        root.right = node2;
        node1.right = node3;

        System.out.println(s.sumNumbers(root));

    }

    public int sumNumbers(Node root) {

        if (root == null)
            return 0;
        stack.push(root.value);


        // root to this leaf load sum
        if (root.left == null && root.right == null) {
            int now = 0;
            for (Integer i : stack) {
                now = now * 10 + i;
            }
            sum += now;


        } else {
            if (root.left != null) {
                sumNumbers(root.left);
                stack.pop();
            }
            if (root.right != null) {
                sumNumbers(root.right);
                stack.pop();
            }

        }
        return sum;
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值