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;    }};


原创粉丝点击