Sum Root to Leaf Numbers 求路径之和

二叉树的建立:

public class PrintPath{

static Scanner in=new Scanner(System.in);//Scanner作为成员变量
   //10 5 4 # # 7 # # 12 # #,一行数据建立二叉树

public static TreeNode Create(TreeNode T){ 
       String a=in.next();//具体是String in看情况
//System.out.println("输入的是"+a);
if(a.equals("#")){
return null;
//System.out.println("---------应该结束了");
}
else{
T=new TreeNode(Integer.parseInt(a));
T.left=Create(T.left);
       T.right=Create(T.right);
}

return T;
   }


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.


还是二叉树递归遍历所有路径,路径为从根到叶子(左右子树皆为null),先把空树情况单列。

然后遍历到叶子,把这条路径之和保存在ArrayList里面,最后遍历数组,求和,即可得出结果!

虽然空树已经排出,if(T==null),依然不能舍去,此句可以解决单分支节点。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 import java.util.*;
public class Solution {
    static ArrayList<Integer> al=null;
    public int sumNumbers(TreeNode root) {
        if (root==null)
         return 0;
         al=new ArrayList<Integer>();
        PathSum(root,0);
        Iterator<Integer> it=al.iterator();
        int zoomSum=0;
	   while(it.hasNext())
	 zoomSum+=it.next();
	return zoomSum;
    }
    public static void PathSum(TreeNode T,int sum){
    if(T==null)
      return ;
    sum=sum*10+T.val;
    if(T.left==null&&T.right==null)
      al.add(sum);
    PathSum(T.left,sum);
    PathSum(T.right,sum);
   }
}
2.如果不想用数组保存每条路径之和,可以以一个res,直接不停求和。

public class Solution {  
    int res ;  
    public int sumNumbers(TreeNode root) {  
        // Note: The Solution object is instantiated only once and is reused by each test case.  
         if(root == null)  
            return 0;  
         res = 0;  
         sumnum(root,0);  
         return res;  
    }  
    public void sumnum(TreeNode root, int tmpsum)  
    {  
        if(root.left == null && root.right == null)  
        {  
            res += tmpsum * 10 + root.val;  
        }  
        if(root.left != null)  
        {  
            sumnum(root.left, tmpsum * 10 + root.val);  
        }  
        if(root.right != null)  
        {  
            sumnum(root.right, tmpsum * 10 + root.val);  
        }  
           
           
    }  
}


时刻记住,二叉树节点的三种类型,树叶,单分支,双分支。

Path Sum

下面这题看看是否存在二叉树路径等于给定数,存在返回true,不存在返回false

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and  sum = 22 ,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

public class Solution {
    static int n;
    public boolean hasPathSum(TreeNode root, int sum) {
      n=sum;
      return ContainSum(root,0);  
    }
     public static boolean ContainSum(TreeNode T,int sum){
    if(T==null)
      return false;
   sum=sum+T.val;
   if(T.left==null&&T.right==null){
     if(sum==n)
	   return true;
	}   
   boolean lflag=ContainSum(T.left,sum);
     if(lflag==true)
     return lflag;
   boolean rflag=ContainSum(T.right,sum);
     if(rflag==true)
	 return rflag;
     return false;//只有完全遍历完全才可以返回false
  }
}  

看看斯坦福的水平

public boolean hasPathSum(int sum) { 
 return( hasPathSum(root, sum) ); 
}

boolean hasPathSum(Node node, int sum) { 
  // return true if we run out of tree and sum==0 
  if (node == null) { 
    return(sum == 0); 
  } 
  else { 
  // otherwise check both subtrees 
    int subSum = sum - node.data; 
    return(hasPathSum(node.left, subSum) || hasPathSum(node.right, subSum)); 
  } 
} 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值