Leectcode Maximum Depth of Binary Tree
来源:互联网 发布:淘宝银行卡 编辑:程序博客网 时间:2024/05/20 13:09
Description: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.
Solution:求二叉树的深度。可以递归也可以非递归。
递归法(Recursion)
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. return dfs(root, 0); } int dfs(TreeNode *root, int depth){ if(!root) return depth; depth++; int right_dep = dfs(root->left, depth); int left_dep = dfs(root->right, depth); return max(right_dep, left_dep); }};
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. if(root == NULL) return 0; queue<TreeNode*> q_node; queue<int> q_dep; q_node.push(root); q_dep.push(1); TreeNode *top_node; int top_dep; while(!q_node.empty()){ top_node = q_node.front(); q_node.pop(); top_dep = q_dep.front(); q_dep.pop(); if(top_node->left != NULL){ q_node.push(top_node->left); q_dep.push(top_dep+1); } if(top_node->right != NULL){ q_node.push(top_node->right); q_dep.push(top_dep+1); } } return top_dep; }};
- Leectcode Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- ※C++随笔※=>☆C++基础☆=>※№→C++中 #include<>与#include""
- Python全局变量在模块之间引用的问题
- ibatis 打印sql出来 log4j.xml与log4j.properties两种方式
- php 验证手机号码格式
- PAT 3-05. 求链式线性表的倒数第K项
- Leectcode Maximum Depth of Binary Tree
- 关于学科导论
- 提取(GridControl数据源只改变若干条记录)datatable中的指定记录(DicTionary)
- 父窗口与子窗口的层次关系
- iphone--------------------------------------
- vc创建文件对话框
- C语言变量声明内存分配(转)
- 线性表
- 中文乱码问题