404. Sum of Left Leaves
来源:互联网 发布:yum安装命令 编辑:程序博客网 时间:2024/04/30 17:39
递归方法:
public int sumOfLeftLeaves(TreeNode root) {
if(root==null){return 0;
}
int sum=0;
Stack<TreeNode> stacknode= new Stack<>();
stacknode.push(root);
while(!stacknode.isEmpty()){
root=stacknode.pop();
if(root.left!=null&&root.left==null&&root.right==null){ //判断左树叶
sum=sum+root.left.val;
}
if(root.left!=null){
stacknode.push(root.left);
}
if(root.right!=null){
stacknode.push(root.right);
}
}
return sum;
}
迭代方法
public int sumOfLeftLeaves(TreeNode root) {
if(root==null){
return 0;
}
if(root.left!=null&&root.left.left==null&&root.left.right==null){
return root.left.val+sumOfLeftLeaves(root.right);
}
else{
return sumOfLeftLeaves(root.right)+sumOfLeftLeaves(root.left);
}
}
先写出了迭代的方法,递归还是掌握不熟练,改了好多次。
0 0
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves*
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- CentOS6.4 增加一个SFTP上传的用户
- 1100. Mars Numbers
- 【GDOI2017模拟9.24】周末晚会
- 最短路径dijkstra-与最小生树prim算法对比
- <sdut-ACM>顺序表应用4:元素位置互换之逆置算法
- 404. Sum of Left Leaves
- 使用nuwa热补丁的编译注入第三方jar类的问题
- PHP实现MVC开发: 一个简单的MVC
- 【线性规划与网络流24题 1】飞行员配对方案
- POJ-3071-Football
- 长尾狐狸(简单dp)
- Java ArrayList LinkedList
- 25补间动画
- 理解回溯法