//
// main.cpp
// test
//
// Created by MaKai on 2017/3/18.
// Copyright © 2017年 MaKai. All rights reserved.
//
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include "cmath"
using namespace std;
struct Node{
int val;
Node* left;
Node* right;
Node(int val){
this->left = this->right = NULL;
this->val = val;
}
};
Node* findSameParent(Node* root, Node* n1, Node* n2);
void findNodePath(string &p, Node* root, Node* node, string s);
int main(int argc, const char * argv[]) {
Node* n1 = new Node(1);
Node* n2 = new Node(2);
Node* n3 = new Node(3);
Node* n4 = new Node(4);
Node* n5 = new Node(5);
Node* n6 = new Node(6);
n1->left = n2;
n1->right = n4;
n2->left = n3;
n2->right = n6;
n4->right = n5;
cout<<findSameParent(n1, n3, n6)->val<<endl;
return 0;
}
Node* findSameParent(Node* root, Node* n1, Node* n2) {
string s1 = "";
string s2 = "";
findNodePath(s1, root, n1, "r");
findNodePath(s2, root, n2, "r");
cout<<s1<<" "<<s2<<endl;
Node* node = root;
for (int i = 1; i < min(s1.size(), s2.size()); i++) {
if (s1[i] == s2[i]) {
if (s1[i] == '0') {
node = node->left;
}else{
node = node->right;
}
}else{
break;
}
}
return node;
}
void findNodePath(string &p, Node* root, Node* node, string s){
if (root == node) {
p = s;
return;
}
if (root->left) {
findNodePath(p, root->left, node, s.append("0"));
s.erase(s.end() - 1);
}
if (root->right) {
findNodePath(p, root->right, node, s.append("1"));
}
}
二叉树寻找两个结点的公共子节点
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 上代码:public Node nearestParentNode(Node head , Node o1 , N...