[leetcode刷题系列]Maximum Depth of Binary Tree

来源:互联网 发布:mac 免费uml建模工具 编辑:程序博客网 时间:2024/05/28 03:03

囧, 继续模拟, 继续指针!


/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {    void dfs(TreeNode * root, int now, int & ans){        ans = max(ans, now);        if(root->left != 0)            dfs(root->left, now + 1, ans);        if(root->right != 0)            dfs(root->right, now + 1, ans);    }public:    int maxDepth(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(root == 0)            return 0;        int ans = 0;        dfs(root, 1, ans);        return ans;    }};