Maximum Depth of Binary Tree
2014-02-27 16:46
211 查看
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.
递归方法,分别求左子树和右子树的深度,然后取二者中大的一个,然后加1就是二叉树的深度。
非递归,利用树的层序遍历,来求最大深度
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
递归方法,分别求左子树和右子树的深度,然后取二者中大的一个,然后加1就是二叉树的深度。
/** * 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) { int depth = 0; if(root) { int lDepth = maxDepth(root -> left); int rDepth = maxDepth(root -> right); if(lDepth >= rDepth) depth = lDepth+1; else depth = rDepth+1; } return depth; } };
非递归,利用树的层序遍历,来求最大深度
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct Node { TreeNode *node; int level; Node(){} Node(TreeNode *n, int l):node(n), level(l){} }; class Solution { public: int maxDepth(TreeNode *root){ // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) return 0; queue<Node> q; q.push(Node(root, 1)); int curLevel = 0; while(!q.empty()) { Node node = q.front(); if (node.node->left) q.push(Node(node.node->left, node.level + 1)); if (node.node->right) q.push(Node(node.node->right, node.level + 1)); if (curLevel != node.level) { curLevel = node.level; } q.pop(); } return curLevel; } };
相关文章推荐
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree--LeetCode
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- leetcode_question_104 Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- leetcode 104: Maximum Depth of Binary Tree
- 【LeetCode OJ】Maximum Depth of Binary Tree
- 30.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(DFS)
- LeetCode_104 Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree 二叉树的最大深度
- [LeetCode#104, 111]Maximum Depth of Binary Tree, Minimum Depth of Binary Tree
- leetcode 日经贴,Cpp code -Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree
- 【LeetCode】Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree 二叉树
- LeetCode--No.104--Maximum Depth of Binary Tree