题目
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的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;
}
}