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.
分析,采用的策略,首先计算树的高度,然后申请最小为树高的内存空间构造栈结构。
采用先左子树优先遍历的方法,将树种的点放到栈中,直到遇到一个点没有左右子树,则判定为叶子结点,然后判断是否满足条件,满足返回结果true;不满足,弹出叶子结点,沿着路经回溯到上个节点,在将上个节点的右节点放入栈中分析。此处,我们使用的小trick是,对于已将左/右子树放入栈中的节点的相应的left/right位置,我们直接赋值为spec(遍历树找到设置为比最小值还小的值),那么回溯时,再遇到这个节点,能观测到的只有未放入栈中的子树。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int height(TreeNode r)
{
if(r==null)
return 0;
else
{
int lh=height(r.left);
int rh=height(r.right);
if(lh>rh)
return lh+1;
else
return rh+1;
}
}
TreeNode[] stack;
int top;
int man;
public void push(TreeNode x)
{
/*
if(x!=null)
{
stack[top].val=x.val;
stack[top].left=x.left;
stack[top].right=x.right;
}
else
stack[top]=null;
*/
stack[top]=x;
top++;
}
public void pop()
{
top--;
}
public TreeNode getTop()
{
return stack[top-1];
}
public boolean isNull()
{
if(top==0)
return true;
else
return false;
}
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null)
return false;
int s=0;
int h=height(root);
stack=new TreeNode[h+1];
for(int i=0;i<h+1;i++)
stack[i]=new TreeNode(0);
top=0;
man=h+1;
push(root);
while(!isNull())
{
TreeNode t=getTop();
s=s+t.val;
if(t.left==null&&t.right==null)
if(s==sum)
return true;
else
{
while(t.left==null&&t.right==null)
{
s=s-t.val;
pop();
if(isNull())
break;
t=getTop();
}
if(isNull())
break;
if(t.left!=null)
{
TreeNode tl=t.left;
t.left=null;
pop();
push(t);
push(tl);
}
if(t.right!=null)
{
TreeNode tr=t.right;
t.right=null;
pop();
push(t);
push(tr);
}
}
else if(t.left==null)
{
TreeNode tr=t.right;
t.right=null;
pop();
push(t);
push(tr);
}
else
{
TreeNode tl=t.left;
t.left=null;
pop();
push(t);
push(tl);
}
}
return false;
}
}