一天一算法(40):二叉树中和为某值的路径

题目

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

思路

又题目可知,正确的路径必须满足两个条件:一是路劲的节点的值之和等于给定的值,二是路劲必须是根节点到叶子节点。这里我使用了二叉树的非递归前序遍历,利用栈来存储路径。

代码

using System.Collections.Generic;
/*
public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode (int x)
    {
        val = x;
    }
}*/

class Solution
{
    public List<List<int>> FindPath(TreeNode root, int expectNumber)
    {
        // write code here
        List<List<int>> list=new List<List<int>>();
        List<int> list2=new List<int>();
        int num=0;
        if(root==null)
            return list;
        if(root.left==null && root.right==null)
        {
            list2.Add(root.val);
            list.Add(list2);
            return list;
        }
        Stack<TreeNode> stack=new Stack<TreeNode>();
        Stack<TreeNode> stack2=new Stack<TreeNode>();
        while(root!=null || stack.Count>0)
        {
            if(root!=null)
            {
                stack.Push(root);
                stack2.Push(root);
                num+=root.val;
                
                if(num==expectNumber &&root.left == null && root.right == null)
                {
                    list2=AddValue(stack2);
                    list.Add(list2);
                }
                root=root.left;
            }
            else if(stack.Count>0)
            {
                root=stack.Pop();
                     if (root.left == null && root.right == null)
                    {
                        stack2.Pop();
                        num -= root.val;
                    }
                    else if (stack2.Peek() != root)
                    {

                        num -= stack2.Pop().val;
                    }
                root=root.right;
            }
        }
        return list;
    }
    
    public List<int> AddValue(Stack<TreeNode> stack1)
    {
        List<int> list=new List<int>();
        Stack<TreeNode> stack2=new Stack<TreeNode>();
        while(stack1.Count>0)
        {
            stack2.Push(stack1.Pop());
        }
        while(stack2.Count>0)
        {
             stack1.Push(stack2.Pop());
             list.Add(stack1.Peek().val);
        }
        return list;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值