您的位置:首页 > 其它

leetcode[Sum of Left Leaves]//待整理多种解法

2017-07-18 16:59 429 查看
解法一:

/**
* 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 sumOfLeftLeaves(TreeNode root) {

int res = 0;
//用递归不好解决求和累加的问题,这里采用迭代的方式来遍历二叉树
//先根遍历
Stack<TreeNode> stack = new Stack<>();
if(root == null) return 0;
TreeNode temp = root;
while(temp != null){//先 将左边全压入,压栈时走左边,压的时候就全是左子节点,这时候就(打印)
stack.push(temp);
/*if(temp.left == null && temp.right == null){
res += temp.val;//将左叶子结点加入结果中
}*/
temp = temp.left;
if(temp != null && temp.left == null && temp.right == null){//不能放在上面注释的位置,要确保是在左边那条路
res += temp.val;//将左叶子结点加入结果中
}
}
//弹栈后走右边,即判断弹出节点的右子节点(因为之前压入栈的结点已经被打印)
while(!stack.isEmpty()){
temp = stack.pop();
temp = temp.right;//得到弹出的右结点
while(temp != null){//压栈时走左边,压的时候就全是左子节点,这时候就(打印)
stack.push(temp);
/*if(temp.left == null && temp.right == null){
res += temp.val;//将左叶子结点加入结果中
}*/
temp = temp.left;
if(temp != null && temp.left == null && temp.right == null){//不能放在上面注释的位置,要确保是在左边那条路
res += temp.val;//将左叶子结点加入结果中
}
}
}

return res;
}
}

解法一(先根遍历)的更简洁形式(只用一个大的循环,实际原理是一样的,形式更简单,理解更复杂):

/**
* 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 sumOfLeftLeaves(TreeNode root) {
int res = 0;
//用递归不好解决求和累加的问题,这里采用迭代的方式来遍历二叉树
//先根遍历
Stack<TreeNode> stack = new Stack<>();
if(root == null) return 0;
TreeNode temp = root;
while(temp != null || !stack.isEmpty()){

while(temp != null){
stack.push(temp);
/*if(temp.left == null && temp.right == null){
res += temp.val;//将左叶子结点加入结果中
}*/
temp = temp.left;
if(temp != null && temp.left == null && temp.right == null){//不能放在上面注释的位置,要确保是在左边那条路
res += temp.val;//将左叶子结点加入结果中
}
}

temp = stack.pop();
temp = temp.right;//得到弹出的右结点
}

return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: