您的位置:首页 > 其它

Sum Root to Leaf Numbers 求路径之和

2014-04-25 20:42 246 查看
二叉树的建立:

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,直接不停求和。

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

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)); 
  } 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: