Question 2. Find distance between two given keys of a Binary Tree, no parent pointers are given. Distance between two nodes is the minimum number of edges to be traversed to reach one node from other.
Assumptions:
There are no duplicate keys in the binary tree.
Assumptions:
There are no duplicate keys in the binary tree.
The given two keys are guaranteed to be in the binary tree.
struct Node{
Node* left, *right;
int val;
};
int Level(Node* root, Node* p){
queue<Node*> q;
q.push(root);
int level=0;
while(!q.empty()){
int qsize=q.size();
for(int i=0;i<qsize;i++){
auto cur=q.front();q.pop();
if(cur==p) return level;
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
level++;
}
}
Node* LCA(Node* root, Node*p1, Node*p2){
if(!root || root==p1 || root==p2) return root;
Node* leftLCA=LCA(root->left, p1, p2);
Node* rightLCA=LCA(root->right, p1, p2);
if(leftLCA && rightLCA) return root;
else if(leftLCA) return leftLCA;
else if(rightLCA) return rightLCA;
else return NULL;
}
int MinDis(Node* root, Node*p1, Node*p2){
Node* lca=LCA(root, p1, p2);
return Level(lca, p1)+Level(lca, p2);
}
LCA加层序遍历 时间ON
http://www.lintcode.com/en/problem/find-the-missing-number/
class Solution {
public:
/**
* @param nums: a vector of integers
* @return: an integer
*/
int findMissing(vector<int> &a) {
int n=a.size();
for(int i=0;i<n;){
if(a[i]!=i && a[i]<n){
swap(a[i], a[a[i]]);
}else{
i++;
}
}
for(int i=0;i<n;i++){
if(a[i]!=i) return i;
}
return n;
}
};
这种题目注意交换过来的数 可能还未处理,因此不能i++,而且可以保证不会出现死循环
这题代码
https://leetcode.com/problems/first-missing-positive/class Solution {
public:
int firstMissingPositive(vector<int>& a) {
int n=a.size();
for(int i=0;i<n;){
if(0<=a[i]-1 && a[i]-1<n && i!=a[i]-1 && a[i]!=a[a[i]-1])
swap(a[i], a[a[i]-1]);
else i++;
}
for(int i=0;i<n;i++){
if(a[i]!=i+1) return i+1;
}
return n+1;
}
};