星空网 > 软件开发 > Java

[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.

 

     这道题我们借助stack和iteration就可以做出来了。

     一个stack<TreeNode>用于node,另一个stack<Integer>用于depth的value。

     代码如下。~

/** * Definition for a binary tree node. * public class TreeNode { *   int val; *   TreeNode left; *   TreeNode right; *   TreeNode(int x) { val = x; } * } */public class Solution {  public int maxDepth(TreeNode root) {    Stack<TreeNode> tree=new Stack<TreeNode>();    Stack<Integer> value=new Stack<Integer>();    int max=0;    if(root==null){      return 0;    }    tree.push(root);    value.push(1);    while(!tree.isEmpty()){      TreeNode temp=tree.pop();      int val=value.pop();      max=Math.max(max,val);      if(temp.right!=null){        tree.push(temp.right);        value.push(val+1);      }      if(temp.left!=null){        tree.push(temp.left);        value.push(val+1);      }    }    return max;  }}

 

    




原标题:[LeetCode] Maximum Depth of Binary Tree

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

图解丨一文看懂进境粮食初审联系单电子化申请流程:https://www.kjdsnews.com/a/1482681.html
游戏出海税收问题怎么解决?:https://www.kjdsnews.com/a/1482682.html
如何有效地进行外贸推广?询多多为您提供外贸网站推广:https://www.kjdsnews.com/a/1482683.html
Temu要求卖家添加生产者延伸责任(EPR)资质备案(内含详细添加步骤):https://www.kjdsnews.com/a/1482684.html
卖货主播逃离618:https://www.kjdsnews.com/a/1482685.html
英国国内度假需求大涨,原因是生活成本上涨及夏日好天气:https://www.kjdsnews.com/a/1482686.html
加拿大本地账户开立是否需要加拿大身份? :https://www.xlkjsw.com/news/92266.html
亚龙湾有什么景点必看 亚龙湾有哪些景点:https://www.vstour.cn/a/408228.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流