题目链接:点击打开链接
题目大意:略
解题思路:略
相关企业
- 领英(LinkedIn)
- 字节跳动
- 亚马逊(Amazon)
- 谷歌(Google)
- 微软(Microsoft)
- 彭博(Bloomberg)
- 苹果(Apple)
AC 代码
- Java
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/// 解决方案(1)classSolution { intres=0; publicintmaxDepth(TreeNoderoot) { dfs(root, 1); returnres; } voiddfs(TreeNodenode, intl) { if (node==null) { return; } res=Math.max(res, l); dfs(node.left, l+1); dfs(node.right, l+1); } } // 解决方案(2)classSolution { publicintmaxDepth(TreeNoderoot) { if(root==null) return0; returnMath.max(maxDepth(root.left), maxDepth(root.right)) +1; } } // 解决方案(3)classSolution { publicintmaxDepth(TreeNoderoot) { if(root==null) return0; List<TreeNode>queue=newLinkedList<>() {{ add(root); }}, tmp; intres=0; while(!queue.isEmpty()) { tmp=newLinkedList<>(); for(TreeNodenode : queue) { if(node.left!=null) tmp.add(node.left); if(node.right!=null) tmp.add(node.right); } queue=tmp; res++; } returnres; } }
- C++
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/// 解决方案(1)classSolution { public: intmaxDepth(TreeNode*root) { if(root==nullptr) return0; returnmax(maxDepth(root->left), maxDepth(root->right)) +1; } }; // 解决方案(2)classSolution { public: intmaxDepth(TreeNode*root) { if(root==nullptr) return0; vector<TreeNode*>que; que.push_back(root); intres=0; while(!que.empty()) { vector<TreeNode*>tmp; for(TreeNode*node : que) { if(node->left!=nullptr) tmp.push_back(node->left); if(node->right!=nullptr) tmp.push_back(node->right); } que=tmp; res++; } returnres; } };