【LeetCode】 Maximum Depth of Binary Tree 二叉树的最大深度

来源:互联网 发布:兴达驾校网络预约系统 编辑:程序博客网 时间:2024/06/06 12:02

二叉树的最大深度
给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的距离。

样例给出一棵如下的二叉树:  1 / \ 2   3   / \  4   5这个二叉树的最大深度为3.

标签
分治法 二叉树 递归 优步

(1)Java

import BinaryTree.TreeNode;// Version 1: Divide Conquerpublic class MaximumDepthOfBinaryTree {    public int maxDepth(TreeNode root) {        if (root == null) {            return 0;        }        int left = maxDepth(root.left);        int right = maxDepth(root.right);        return Math.max(left, right) + 1;    }}// version 2: Traverse/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } *///dfs:public class Solution {    /**     * @param root: The root of binary tree.     * @return: An integer.     */    private int depth;    public int maxDepth(TreeNode root) {        depth = 0;        helper(root, 1);        return depth;    }    private void helper(TreeNode node, int curtDepth) {        if (node == null) {            return;        }        if (curtDepth > depth) {//在此处更新depth的值。(即:前一次node有左/右子节点,故这一次depth需要+1)            depth = curtDepth;        }        helper(node.left, curtDepth + 1);        helper(node.right, curtDepth + 1);    }}

(2)C++

// Version 1: Divide Conquerclass Solution {    public:    /**     * @param root: The root of binary tree.     * @return: An integer     */    int maxDepth(TreeNode *root) {        if (root == NULL) {            return 0;        }        int left = maxDepth(root->left);        int right = maxDepth(root->right);        return left > right ? left + 1 : right + 1;    }};//Version 2 : dfs ( Traverse )class Solution {    public:    int depth;    void helper(TreeNode* root, int curtDepth){        if(root == NULL){            return;        }        if(curtDepth > depth){            depth = curtDepth;        }        helper(root->left, curtDepth + 1);        helper(root->right, curtDepth + 1);    }    int maxDepth(TreeNode *root) {        depth = 0;//初始化        if(root == NULL){            return 0;        }        helper(root, 1);        return depth;    }};
阅读全文
0 0
原创粉丝点击