标签:
public static class Node { Node left = null; Node right = null; Object data = null; Node parent = null; int leftLen;//求距离最远的节点 int rightLen; public Node(){ } public Node(Object data){ this.data = data; } public Node(Object data, Node left, Node right, Node parent ){ this.data = data; this.left = left; this.right = right; this.parent = parent; }
}
1
2
3 4
5 6 X 7
8
public static int getDepth(Node head) { if (head == null) return 0; else { int left = getDepth(head.left); int right = getDepth(head.right); System.out.print("Node" + head.data + "\t"); return 1 + Math.max(left, right); } }
public static int getWidth(Node head) { if (head == null) return 0; Queue<Node> queue = new ArrayDeque<Node>(); queue.add(head); int maxWidth = 1; while (true) { int len = queue.size(); if (len == 0) break; while (len > 0) { Node tmp = queue.poll(); len--; System.out.print(tmp.data); if (tmp.left != null) queue.add(tmp.left); if (tmp.right != null) queue.add(tmp.right); } maxWidth = Math.max(maxWidth, queue.size()); } return maxWidth; }
计算一个二叉树的最大距离有两个情况:
1.路径经过左子树的最深节点,通过根节点,再到右子树的最深节点。
2.路径不穿过根节点,而是左子树或右子树的最大距离路径,取其大者。
public static int maxLenGet(Node head) { if (head == null) return 0; if (head.left != null) { head.leftLen = maxLenGet(head.left) + 1; System.out.println("Node" + head.data + ".LeftLen ->" + head.leftLen); } else { head.leftLen = 0; System.out.println("Node" + head.data + ".left=null"); } if (head.right != null) { head.rightLen = maxLenGet(head.right) + 1; System.out.println("Node" + head.data + ".RightLen ->" + head.rightLen); } else { head.rightLen = 0; System.out.println("Node" + head.data + ".right=null"); } if (head.rightLen + head.leftLen > maxDistance) { maxDistance = head.rightLen + head.leftLen; } return head.rightLen > head.leftLen ? head.rightLen : head.leftLen; }
标签:
原文地址:http://www.cnblogs.com/zhaoqi3215/p/4987296.html