题目

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.

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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值