LeetCode oj 104. Maximum Depth of Binary Tree(DFS||BFS)

来源:互联网 发布:快搜 知乎 编辑:程序博客网 时间:2024/06/08 11:47

104. Maximum Depth of Binary Tree

 
 My Submissions
  • Total Accepted: 179819
  • Total Submissions: 361510
  • Difficulty: Easy

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Subscribe to see which companies asked this question

求二叉树的深度

题很水,DFS和BFS都可以

BFS:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int count = 0;    public int maxDepth(TreeNode root) {        Queue<TreeNode> q = new LinkedList<TreeNode>();if(root == null)return 0;q.clear();q.add(root);while(!q.isEmpty()){count++;int len = q.size();for(int i=0;i<len;i++){TreeNode t = q.poll();if(t.left != null){q.add(t.left);}if(t.right != null){q.add(t.right);}}}return count;}}
DFS:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int maxDepth(TreeNode root) {      if(root == null){return 0;}if(root.left == null && root.right == null){return 1;}int Depth_left = maxDepth(root.left);int Depth_right = maxDepth(root.right);return Math.max(Depth_left,Depth_right) + 1;}}


0 0