Leetcode Maximum Depth of Binary Tree

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.

递归求解

int maxDepth(TreeNode *root){
    return root? 1+max(maxDepth(root->left), maxDepth(root->right)) : 0;
}

 非递归求解

struct Node{
    TreeNode *node;
    int depth;
    Node(TreeNode *a = NULL , int d = 0):node(a), depth(d);
};

int maxDepth1(TreeNode *root){
    if(root == NULL) return 0;
    queue<Node> que;
    Node  rootNode(root,1);
    que.push(rootNode);
    int res = 0;
    while(!que.empty()){
        Node p = que.front();que.pop();
        res = p.depth;
        if(p.node->left)    que.push(Node(p.node->left,p.depth+1));
        if(p.node->right )  que.push(Node(p.node->right,p.depth+1));
    }
    return res;
}

 

posted @ 2014-06-22 23:21  OpenSoucre  阅读(125)  评论(0编辑  收藏  举报