Find Distance in a Binary Tree
给一个二叉树, 求树上任意两点之间有多少个边. 图论基础题, 先找lca.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
/** * 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; } } |