Find Distance in a Binary Tree
给一个二叉树, 求树上任意两点之间有多少个边. 图论基础题, 先找lca.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int findDistance(TreeNode root, int p, int q) {
TreeNode lca = lca(root, p, q);
return distance(lca, p, 0) + distance(lca, q, 0);
}
public int distance(TreeNode root, int p, int depth) {
if(root == null)
return Integer.MAX_VALUE; // unreachable
if(root.val == p)
return depth;
return Math.min(distance(root.left, p, depth + 1), distance(root.right, p, depth + 1));
}
public TreeNode lca(TreeNode root, int p, int q) {
if(root == null)
return root;
if(root.val == p)
return root;
if(root.val == q)
return root;
TreeNode l = lca(root.left, p, q);
TreeNode r = lca(root.right, p, q);
if(l == null)
return r;
if(r == null)
return l;
return root;
}
}