236. Lowest Common Ancestor of a Binary Tree
lc-236
朴素解法及优化解法。
朴素解法:
考虑寻找 0,8 的最近公共祖先。可以先找到各自的路径:
path_p = 3 1 0
path_1 = 3 1 8
然后找到第一对不同的数(0,8)往前的数(1),就是答案。
class Solution { public: void FindPathImpl(stack<TreeNode *> &history, TreeNode *root, TreeNode *target, bool &over) { if (over) { return; } history.push(root); if (root == nullptr) { return; } if (root == target) { over = true; return; } FindPathImpl(history, root->left, target, over); if (over) { return; } else { history.pop(); } FindPathImpl(history, root->right, target, over); if (over) { return; } else { history.