Leetcode 之 Maximum Depth of Binary Tree

先序遍历比较简单

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (nullptr == root) return 0;
        stack<TreeNode *> deepFirstStack;
        int max_depth = 0, cur_depth = 0;
        while (nullptr != root) {
            if (++cur_depth > max_depth) max_depth = cur_depth; 
            if (nullptr != root->left) {
                if (nullptr != root->right) {
                    root->right->val = cur_depth;
                    deepFirstStack.push(root->right);
                }
                root = root->left;
            } else if (nullptr != root->right) {
                root = root->right;
            } else {
                if (deepFirstStack.empty()) return max_depth;
                root = deepFirstStack.top();
                cur_depth = root->val;
                deepFirstStack.pop();
            }
        }
        return max_depth;
    }
};
原文地址:https://www.cnblogs.com/Dream-Fish/p/4819567.html