Find distance between two given keys of a Binary Tree
2015-01-05 21:46
351 查看
Find the distance between two keys in 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.
另外请参考:http://www.geeksforgeeks.org/find-distance-two-given-nodes/
另外请参考:http://www.geeksforgeeks.org/find-distance-two-given-nodes/
#include <iostream> using namespace std; #define INF 1e9 struct Node { int value; Node *left, *right, *parent; Node(int _value) { value = _value; left = NULL; right = NULL; } }; int find_level(Node *node, int value, int level) { if (!node) { return INF; } if (node->value == value) { return level; } return min( find_level(node->left, value, level + 1), find_level(node->right, value, level + 1) ); } Node *lca(Node *node, int n1, int n2) { if (!node) { return NULL; } if (node->value == n1 || node->value == n2) { return node; } Node *left = lca(node->left, n1, n2); Node *right = lca(node->right, n1, n2); if (left && right) { return node; } return left != NULL ? left : right; } int solve(Node *r, int n1, int n2) { return find_level(r, n1, 0) + find_level(r, n2, 0) - 2 * find_level(r, lca(r, n1, n2)->value, 0); } int main() { // 4 // 2 6 // 1 3 5 7 Node *r = new Node(4); r->left = new Node(2); r->right = new Node(6); r->left->left = new Node(1); r->left->right = new Node(3); r->right->left = new Node(5); r->right->right = new Node(7); cout << solve(r, 1, 7) << endl; return 0; }
相关文章推荐
- find distance between two nodes in a binary tree
- geeksforgeeks Find the maximum path sum between two leaves of a binary tree
- Find the common ancestor of two nodes in a binary tree
- Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never diffe
- Given a sequence of numbers (or array).Find the maximum distance between all the same numbers.
- Find the nearest common ancestor of any two nodes in a binary search tree
- 数组空间Given a sequence of numbers (or array).Find the maximum distance between all the same numbers.
- [面试题]Amazon: Given two binary trees,if the first tree is subtree of the second one
- [geeks]Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST
- [LeetCode] Find Leaves of Binary Tree 找二叉树的叶节点
- [Tree]If you are given two traversal sequences, can you construct the binary tree?
- Write a function to find the depth of a binary tree
- ch4.7: given 2 huge Binary tree t1, t2(>1millon nodes), decide if one tree is subtree of another one
- Find deepest node(s) of a binary tree
- Given a tree, find the node with the minimum sum of distances to other nodes
- 二叉树的高度 - 父节点序列 Find Height of Binary Tree by Parent Array
- Data Structure Array: Find the minimum distance between two numbers
- 366. Find Leaves of Binary Tree
- Find Leaves of Binary Tree
- Leetcode: Find Leaves of Binary Tree