TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { stack<TreeNode*> stk; if (root) stk.push(root); while (!stk.empty()) { root = stk.top(); stk.pop(); if (root) { stk.push(root); stk.push(nullptr); if (root->right) stk.push(root->right); if (root->left) stk.push(root->left); } else { root = stk.top(); stk.pop(); if ((root->left == p &;;&;; root->right == q) || (root->left == q &;;&;; root->right == p)) return root; if (root == p &;;&;; (root->left == q || root->right == q)) return root; if (root == q &;;&;; (root->left == p || root->right == p)) return root; if (root->left == p || root->right == p) p = root; if (root->left == q || root->right == q) q = root; } } return nullptr; }

相关推荐

牛客网
牛客企业服务