您的位置:首页 > 职场人生

谷歌面试题代码:二叉树结点之间的路径

2016-06-08 22:36 323 查看
题目以及参考思路在这里:二叉树结点之间的路径

参考代码在这里:

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

struct Node
{
int key;
struct Node *left, *right;
};

Node * newNode(int k)
{
Node *temp = new Node;
temp->key = k;
temp->left = temp->right = NULL;
return temp;
}

bool findPath(Node *root, vector<int> &path, int k)
{

if (root == NULL) return false;

path.push_back(root->key);

if (root->key == k)
return true;
if ((root->left && findPath(root->left, path, k)) ||
(root->right && findPath(root->right, path, k)))
return true;
path.pop_back();
return false;
}

int findLCA(Node *root, int n1, int n2)
{
vector<int> path1, path2;

if (!findPath(root, path1, n1) || !findPath(root, path2, n2))
return -1;

int i;
int j;
for (i = 0; i < path1.size() && i < path2.size(); i++)
if (path1[i] != path2[i])
break;
//return path1[i - 1];
j = i-1;
for (i = path1.size()-1; i>=j; i--){

cout << path1[i];
}
for (i = j+1; i <=path2.size()-1; i++){

cout << path2[i];
}

}

int _tmain(int argc, _TCHAR* argv[])
{
Node * root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
findLCA(root,4,7);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试题 数据结构