path_sum2

题目描述

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

          5
         / \
        4   8
       /   / \
      11  13  4
     /  \    / \
    7    2  5   1

return

[

[5,4,11,2],

[5,8,4,5]

]

解题思路

做此题前可以先尝试path_sum,判断二叉树是否存在一条根节点到叶子节点路径使得数值和等于sum,这里则是求出所有的这样的路径集合。

原先的递归关键点是对左右儿子节点递归,左右有一个返回true,当前函数就返回true,现在我们是计算路径,所以每个节点都需要对左右子树遍历,对于符合条件的路径加入到结果结合中。

为了找到一条路径,我定义了一个SuperNode,可以记录其前驱,数据结构如下:

 public class SuperNode {
     int val;
     SuperNode pre;//指向前驱节点
     public SuperNode(int x) 
        { 
            val = x; 
            pre = null;
        }
 }

每次经过一个节点,我们都建立一个supernode sn,标记该节点的val,以及其前驱,如果找到一条符合条件的通路,则把这个sn加入到我们的节点结合List中,最后对list遍历,对其中每个元素sn,进行找前驱的方式,可以得到一条路径,然后放到路径集合中。

详细代码

//path sum2
public List<List<Integer>> pathSum(TreeNode root, int sum) 
{
    List<List<Integer>> resultLists = new ArrayList<>();//结果路径集合
    List<SuperNode> superNodes = new ArrayList<>();//supernodes 集合,每个supernode可以生成一条路径。
    if(root == null)
    {
        return resultLists;
    }
    findPathSum(root, sum, new SuperNode(root.val), superNodes);
    for(SuperNode sn:superNodes)//对supernodes进行遍历,每个node生成一条路径
    {
        List<Integer> lists = new LinkedList<>(); //利用链表插入提高效率
        while(sn != null)
        {
            lists.add(0, sn.val);
            sn = sn.pre;
        }
        resultLists.add(lists);
    }
    return resultLists;
}

 public class SuperNode {
     int val;
     SuperNode pre;//指向前驱节点
     public SuperNode(int x) 
        { 
            val = x; 
            pre = null;
        }
 }

//找到指定路径 返回null为没有 否则可以根据node遍历得到逆序
public void findPathSum(TreeNode root, int sum, SuperNode sn, List<SuperNode> superNodes) {
    if(root == null)
    {
        //空树  结束条件之一
        return;
    }
    else 
    {
        if(root.left==null && root.right==null)
        {
            //叶子节点 left right都为空
            if(sum== root.val)
            {
                superNodes.add(sn);
                return;
            }
            else 
            {
                return;
            }
        }
        else 
        {
            //非叶子结点
            if(root.left != null)
            {
                SuperNode node = new SuperNode(root.left.val);
                node.pre = sn;
                findPathSum(root.left, sum-root.val,node, superNodes);

            }
            if(root.right != null)
            {
                SuperNode node = new SuperNode(root.right.val);
                node.pre = sn;
                findPathSum(root.right, sum-root.val,node, superNodes);

            }

        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章