题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
http://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; * * C语言声明定义全局变量请加上static,防止重复定义 */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param sum int整型 * @return bool布尔型 */ #define ElemType LNode* typedef struct TreeNode LNode; #define bool int //栈结点 typedef struct SNode { struct SNode* next; ElemType e; }SNode; int isEmpty(SNode* S) { if (S == NULL)return 1; else return 0; } int Push(SNode** S, ElemType f) { SNode* x = (SNode*)malloc(sizeof(SNode)); if (x == NULL)return 0; x->e = f; x->next = *S; *S = x; return 1; } int Pop(SNode** S, ElemType* e) { *e = (*S)->e; SNode* p = *S; *S = (*S)->next; free(p); p = NULL; return 1; } bool hasPathSum(struct TreeNode* root, int sum ) { // write code here if(root==NULL)return 0; SNode* S = NULL; LNode* p = root; LNode* r = NULL; int value = 0; while (p || !isEmpty(S)) { if (p) { Push(&S, p); value += p->val; p = p->left; } else { p = S->e; if (p->right && p->right != r) {//若右子树存在,且未被访问过 p = p->right; } else { if (S->e->left == NULL && S->e->right == NULL&&value==sum) { return 1; } Pop(&S, &p); value -= p->val; r = p;//记录最近访问过的结点 p = NULL;//结点访问完后,重置p指针 } } } return 0; }