We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
可以利用深度优先遍历和递归的思路
/** * 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; };
也可以利用广度优先遍历和栈的思路
/** * 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/
The text was updated successfully, but these errors were encountered:
No branches or pull requests
答案1
可以利用深度优先遍历和递归的思路
答案2
也可以利用广度优先遍历和栈的思路
leetcode原题地址:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/
The text was updated successfully, but these errors were encountered: