class Solution4 { public: bool hasPathSum(TreeNode *root, int sum) { if (!root) return false;
bool ret = false; TreeNode* nd = root; while (nd) { if (!nd->left) { //NOTE: can not write `return true` here. since morris traversion modified //struture of tree, we need to run over to make sure all changes restored. //because of this, this may not as fast as primitive solution. if (!nd->right && nd->val == sum) ret = true; if (nd->right) nd->right->val += nd->val; nd = nd->right; } else { auto* l = nd->left; while (l->right && l->right != nd) l = l->right; if (l->right == nd) { if (!l->left && l->val == sum) ret = true; nd = nd->right; l->right = nullptr; } else { nd->left->val += nd->val; if (nd->right) nd->right->val += nd->val; l->right = nd; nd = nd->left; } } }