谷歌面试题代码:二叉树结点之间的路径
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);
参考代码在这里:
#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; }
相关文章推荐
- 一个关于if else容易迷惑的问题
- C#数据结构之顺序表(SeqList)实例详解
- Lua教程(七):数据结构详解
- 一道sql面试题附答案
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构之队列(Quene)实例详解
- C#数据结构揭秘一
- C# 超高面试题收集整理
- C#数据结构之单链表(LinkList)实例详解
- 数据结构之Treap详解
- 人人网javascript面试题 可以提前实现下
- 用C语言举例讲解数据结构中的算法复杂度结与顺序表
- C#数据结构之堆栈(Stack)实例详解
- C#数据结构之双向链表(DbLinkList)实例详解
- JavaScript数据结构和算法之图和图算法
- PHP中设置一个严格30分钟过期Session面试题的4种答案
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- 据说是雅虎的一份PHP面试题附答案
- php牛逼的面试题分享
- 一套比较完整的javascript面试题(部分答案)