面试笔试整理6:常见面试编程题

来源:互联网 发布:电脑网络格斗游戏 编辑:程序博客网 时间:2024/05/18 00:06

1、二叉树公共父节点
leecode236
递归解法:

class Solution {public:    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {        if(root==NULL || root==p||root==q) return root;        TreeNode *left = lowestCommonAncestor(root->left, p, q);        TreeNode *right = lowestCommonAncestor(root->right, p, q);        if(left && right) return root;        return left?left:right;    }};

非递归解法,最简单就是记录节点的父节点和其中一条路径:

class Solution(object):    def lowestCommonAncestor(self, root, p, q):        """        :type root: TreeNode        :type p: TreeNode        :type q: TreeNode        :rtype: TreeNode        """        stack = [root]        pair = {root:None}        while p not in pair or q not in pair:            node = stack.pop()            if node.left:                stack.append(node.left)                pair[node.left] = node            if node.right:                stack.append(node.right)                pair[node.right] = node        #找到到达p的路径        path = set()        while p :            path.add(p)            p = pair[p]        while q not in path:            q = pair[q]        return q 

2、树的中序遍历

//非递归中序遍历void inorderTraversal(TreeNode *root, vector<int> &path){    stack<TreeNode *> s;    TreeNode *p = root;    while(p != NULL || !s.empty())    {        while(p != NULL)        {            s.push(p);            p = p->left;        }        if(!s.empty())        {            p = s.top();            path.push_back(p->val);            s.pop();            p = p->right;        }    }}

递归版:

void inorder(TreeNode *root, vector<int> &path){    if(root != NULL)    {        inorder(root->left, path);        path.push_back(root->val);        inorder(root->right, path);    }}

3、求两个已排序数组的交集
对于两个排序数组很简单,分别找两个指针指向数组头部,如果一个比另一个小就移动小的;如果相等就保存,同时两个指针都移动

public LinkedList<Integer> intersection(int[] A, int[] B) {      if (A == null || B == null || A.length == 0 || B.length == 0) return null;      LinkedList<Integer> list = new LinkedList<Integer>();      int pointerA = 0;      int pointerB = 0;      while (pointerA < A.length && pointerB < B.length) {          if (A[pointerA] < B[pointerB]) pointerA++;          else if (A[pointerA] > B[pointerB]) pointerB++;          else {              list.add(A[pointerA]);              pointerA++;              pointerB++;          }      }      return list;  }  

对于多个数组的情况同样可以用上面的方法或者:首先找到最短的数组,接着对这个数组中的值用二分查找在其他数组中寻找。

原创粉丝点击