[关闭]
@XQF 2018-03-07T23:00:52.000000Z 字数 807 阅读 811

如何求二叉树中的结点最大距离?

数据结构与算法


问题描述:结点的距离是指这两个点之间的边的个数

先找到左子树中离根最远的,再找到右子树中离根最远的。加起来就OK了。

  1. class TreeNode {
  2. int data;
  3. TreeNode left;
  4. TreeNode right;
  5. int leftMaxDis;
  6. int rightMaxDis;
  7. public TreeNode(int data) {
  8. this.data = data;
  9. this.left = null;
  10. this.right = null;
  11. }
  12. }
  13. class BinaryTree {
  14. private int maxLen = 0;
  15. public void findMaxDis(TreeNode root) {
  16. if (root == null) {
  17. return;
  18. }
  19. if (root.left == null) {
  20. root.leftMaxDis = 0;
  21. }
  22. if (root.right == null) {
  23. root.rightMaxDis = 0;
  24. }
  25. if (root.left != null) {
  26. findMaxDis(root.left);
  27. }
  28. if (root.right != null) {
  29. findMaxDis(root.right);
  30. }
  31. if (root.left != null) {
  32. root.leftMaxDis = Math.max(root.left.leftMaxDis, root.left.rightMaxDis) + 1;
  33. }
  34. if (root.right != null) {
  35. root.rightMaxDis = Math.max(root.right.leftMaxDis, root.right.rightMaxDis) + 1;
  36. }
  37. int temp = root.leftMaxDis + root.rightMaxDis;
  38. if (temp > maxLen) {
  39. maxLen = temp;
  40. }
  41. }
  42. }
  43. public class Solution {
  44. public static void main(String[] args) {
  45. }
  46. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注