leetcode Maximum Depth of Binary Tree
来源:互联网 发布:开淘宝店的 编辑:程序博客网 时间:2024/06/06 15:43
解题思路:
深度优先遍历二叉树,
先遍历左孩子,一直到叶子节点,然后回溯,用栈来回溯,遍历右孩子。用栈表示哪些节点有被访问过。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode* root) { int depth = 0; int max_depth = 0; stack<TreeNode*> nodes; set<TreeNode*> visited_nodes; if(root == NULL) return 0; nodes.push(root); depth++; visited_nodes.insert(root); while(true){ if(root == NULL) return max_depth; if((root->left != NULL)&&(visited_nodes.find(root->left)==visited_nodes.end())){ nodes.push(root->left); visited_nodes.insert(root->left); root = root->left; depth++; } else if((root->right != NULL)&&(visited_nodes.find(root->right)==visited_nodes.end())){ nodes.push(root->right); visited_nodes.insert(root->right); root = root->right; depth++; } else{ if((root->right == NULL)&&(root->left) == NULL){ if(depth >= max_depth) max_depth = depth; } if(nodes.empty()){ return max_depth; } nodes.pop(); if(nodes.empty()) return max_depth; root = nodes.top(); depth--; } } }};
0 0
- Leetcode - Tree - Maximum Depth of Binary Tree
- [leetcode][tree] Maximum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- [Leetcode] Maximum Depth of Binary Tree
- leetcode 24: Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- [LeetCode]Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- Leetcode: Maximum Depth of Binary Tree
- LeetCode-Maximum Depth of Binary Tree
- [leetcode] Maximum Depth of Binary Tree
- LeetCode - Maximum Depth of Binary Tree
- LeetCode:Maximum Depth of Binary Tree
- LeetCode | Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- java的list几种实现方式的效率(ArrayList、LinkedList、Vector、Stack),以及 java时间戳的三种获取方式比较
- poj 3696 The Luckiest number 欧拉函数在解a^x=1modm的应用
- 文件上传的三种方式-Java
- hdu 2842(矩阵快速幂+递推)
- 微信公众平台智能回复机器人后台开发
- leetcode Maximum Depth of Binary Tree
- ListView
- 第十四周项目2-用文件保存的学生名单
- C# 透明背景Panel, 透明图像, PitureBox透明效果
- JAVA使用类装载器装载配置文件
- VpnService
- 远程连接虚拟机,怎样将窗体模式转换为全屏模式???
- git 使用记录
- java 日志 自定义过滤