力扣-104-二叉樹的最大深度
阿新 • • 發佈:2020-08-02
題目分析:
方法一:遞迴
求解根節點的最大深度,可以轉化為根節點的深度$1$,加上左子樹和右子樹的最大深度中較大的那一個。通過分析,這明顯是一個遞迴問題,用遞迴求解程式碼也比較簡單。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include<algorithm> using namespace std; class Solution { public: int maxDepth(TreeNode* root) { if (root == NULL) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } };
方法二:$bfs$
求解樹的最大深度,實際上可以通過bfs進行層次遍歷,然後每遍歷一層,$result$加一,$bfs$實現二叉樹的層序遍歷同上題。
/*二叉樹求樹的最大深度使用bfs*/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <queue> #include <vector> using namespace std; class Solution { public: int maxDepth(TreeNode* root) {int result = 0; queue<TreeNode*> tree; if (root!= NULL) tree.push(root); while(!tree.empty()){ int num = tree.size(); for(int i = 0; i < num; i++){ TreeNode* node = tree.front(); tree.pop(); if(node->left != NULL) tree.push(node->left); if(node->right != NULL) tree.push(node->right); } result += 1; } return result; } };