请教大家一个问题:Maximum Height (Depth) of a Binary Tree Using PreOrder Traversal# JobHunting - 待字闺中
c*7
1 楼
各位高手,我想用 Pre-Order Traversal 来实现 maxDepth()。 我用了个hashmap来
保存各个节点的高度.不知道有没有跟优化的解法, 谢谢了!
Here is my code:
public static int maxDepth_preOrderTraversal(TreeNode root){
int maxHight =1;
HashMap nodeHashMap = new HashMap();
if (root==null) return 0;
Stack nodeStack = new Stack();
TreeNode curNode;
nodeStack.push(root);
nodeHashMap.put(root, 1);
while(!nodeStack.isEmpty()){
curNode = nodeStack.pop();
if(curNode.right!=null){
nodeStack.push(curNode.right);
nodeHashMap.put(curNode.right, nodeHashMap.get(curNode)+1);
}
if(curNode.left!=null){
nodeStack.push(curNode.left);
nodeHashMap.put(curNode.left, nodeHashMap.get(curNode)+1);
}
}
// go through the hashmap and find the node with largest height
for (TreeNode node :nodeHashMap.keySet()){
if (nodeHashMap.get(node) > maxHight)
maxHight = nodeHashMap.get(node);
}
return maxHight;
}
保存各个节点的高度.不知道有没有跟优化的解法, 谢谢了!
Here is my code:
public static int maxDepth_preOrderTraversal(TreeNode root){
int maxHight =1;
HashMap nodeHashMap = new HashMap();
if (root==null) return 0;
Stack nodeStack = new Stack();
TreeNode curNode;
nodeStack.push(root);
nodeHashMap.put(root, 1);
while(!nodeStack.isEmpty()){
curNode = nodeStack.pop();
if(curNode.right!=null){
nodeStack.push(curNode.right);
nodeHashMap.put(curNode.right, nodeHashMap.get(curNode)+1);
}
if(curNode.left!=null){
nodeStack.push(curNode.left);
nodeHashMap.put(curNode.left, nodeHashMap.get(curNode)+1);
}
}
// go through the hashmap and find the node with largest height
for (TreeNode node :nodeHashMap.keySet()){
if (nodeHashMap.get(node) > maxHight)
maxHight = nodeHashMap.get(node);
}
return maxHight;
}