的高度我複製此代碼http://www.geeksforgeeks.org/iterative-method-to-find-height-of-binary-tree/怪胎怪才方法找到BST
其中消除隊列目前的水平和排隊的所有節點下一級的所有節點正在發生的事情
// An iterative java program to find height of binary tree
import java.util.LinkedList;
import java.util.Queue;
// A binary tree node
class Node {
int data;
Node left, right;
Node(int item) {
data = item;
left = right;
}
}
class BinaryTree {
static Node root;
// Iterative method to find height of Bianry Tree
int treeHeight(Node node) {
// Base Case
if (node == null) {
return 0;
}
// Create an empty queue for level order tarversal
Queue<Node> q = new LinkedList();
// Enqueue Root and initialize height
q.add(node);
int height = 0;
while (1 == 1) {
// nodeCount (queue size) indicates number of nodes
// at current lelvel.
int nodeCount = q.size();
if (nodeCount == 0) {
return height;
}
height++;
/*
This is the part where I'm very much confused , I can understand that the peek out the 1st node in queue to newnode and removes the 1st node in queue ..
The part I can't understand is why we add nodes to that 1st position and decrease nodeCount at the end of each loop just for running the while loop until queue gets empty ???
So won't we have 0 as q.size() value later ??? I'm damn confused guys !!! Help me !!!
*/
// Dequeue all nodes of current level and Enqueue all
// nodes of next level
while (nodeCount > 0) {
Node newnode = q.peek();
q.remove();
if (newnode.left != null) {
q.add(newnode.left);
}
if (newnode.right != null) {
q.add(newnode.right);
}
nodeCount--;
}
}
}
// Driver program to test above functions
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Height of tree is " + tree.treeHeight(root));
}
}
我無法理解的部分
什麼是您的具體問題? – Yar
使用調試器來通過程序 – Amit