Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉树的最大深度 #18

Open
JesseZhao1990 opened this issue Jul 1, 2018 · 0 comments
Open

二叉树的最大深度 #18

JesseZhao1990 opened this issue Jul 1, 2018 · 0 comments

Comments

@JesseZhao1990
Copy link
Owner

JesseZhao1990 commented Jul 1, 2018

image

答案1

可以利用深度优先遍历和递归的思路

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    if(root === null) return 0;
    return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
};

答案2

也可以利用广度优先遍历和栈的思路

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    if(root ===null ) return 0;
    
    var depth = 1
    var stack = [];
    root.depth=1;
    stack.push(root);
    
    while(stack.length>0){
        var node = stack.shift();
        if(node.left){
           depth = node.left.depth = node.depth+1;
           stack.push(node.left) 
        }
        if(node.right){
            depth =  node.right.depth = node.depth+1;
            stack.push(node.right);
        }  
    }
    return depth;
    
};

leetcode原题地址:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant