Depth of binary tree
Title description
Enter a binary tree and find the depth of the tree. The nodes (including roots and leaf nodes) passing through from the root node to the leaf node in turn form a path of the tree, and the length of the longest path is the depth of the tree.
enter
{1,2,3,4,5,#,6,#,#,7}
return value
4
As soon as I saw the topic, I actually thought of using recursion, but I couldn't figure it out anyway. Really, typing code is most avoiding fantasy. In fact, when you start typing, your ideas will slowly come out. I really need to get rid of this bad habit in the future.
Method one (recursive, the amount of code is small, the most important thing is to solve the idea)
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
// 到了根节点就返回0
if(root == null)
return 0;
// 遍历左节点
int left = TreeDepth(root.left);
// 遍历右节点
int right = TreeDepth(root.right);
// 深度+1
return Math.max(left,right)+1;
}
}
Method two (non-recursive), using queues, count is the current node, nextcount is the total node of the current depth. [Always traverse to the last node of the current depth before the depth increases by 1]
import java.util.LinkedList;
import java.util.Queue;
public int TreeDepth1(TreeNode root) {
if(root==null) {
return 0;
}
Queue<TreeNode> q=new LinkedList<TreeNode>();
q.add(root);
int d=0,count=0,nextcount=q.size();
while(q.size()!=0) {
TreeNode t=q.poll();
count++;
if(t.left!=null) {
q.add(t.left);
}
if(t.right!=null) {
q.add(t.right);
}
// 当把当前深度的所有节点都遍历过后,深度加一,跳到下一深度
if(count==nextcount) {
d++;
// 当前节点重置
count=0;
nextcount=q.size(); // 保存最后节点
}
}
return d;
}