104. Maximum Depth of Binary Tree
2016-08-29 00:15
387 查看
递归
class Solution { public: int maxDepth(TreeNode* root) { if(root==0) return 0; return 1+max(maxDepth(root->left), maxDepth(root->right));/*root!=NULL depth>=1*/ } };
DFS
class Solution { public: int maxDepth(TreeNode* root) { if(root==NULL) return 0; stack<TreeNode*> nodes; //save traversal nodes int result=0; //save max depth of node nodes.push(root); root->val=1; while(nodes.size()>0) { TreeNode* top=nodes.top(); nodes.pop(); int curDepth=top->val; result=result>curDepth?result:curDepth; if(top->left!=NULL) { nodes.push(top->left); top->left->val=curDepth+1; } if(top->right!=NULL) { nodes.push(top->right); top->right->val=curDepth+1; } } return result; } };
BFS
class Solution { public: int maxDepth(TreeNode* root) { if(root==NULL) return 0; queue<TreeNode*> nodes; nodes.push(root); root->val=1; int result=0; while(nodes.size()) { TreeNode *fro=nodes.front(); int curdepth=fro->val; nodes.pop(); result=result>curdepth?result:curdepth; if(fro->left) { nodes.push(fro->left); fro->left->val=curdepth+1; } if(fro->right) { nodes.push(fro->right); fro->right->val=curdepth+1; } } return result; } };
相关文章推荐
- leetcode[110]:Balanced Binary Tree
- Binary Tree Level Order Traversal II
- CSU-ACM 1005: Binary Search Tree analog
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] Validate Binary Search Tree & Recover Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- leetcode235. Lowest Common Ancestor of a Binary Search Tree
- leetcode 110. Balanced Binary Tree
- 104. Maximum Depth of Binary Tree (二叉树)
- Remove Node in Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- binary-tree-level-order-traversal
- 102. Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal
- LeetCode笔记:Convert Sorted Array to Binary Search Tree
- 1064. Complete Binary Search Tree (30)
- [LeetCode] Minimum Depth of Binary Tree
- leetcode 110.Balanced Binary Tree
- Construct Binary Tree from Preorder and Inorder Traversal
- [Random Coding] De/Serialization Binary Tree