您的位置:首页 > 其它

leedcode一刷--Binary Tree

2017-04-07 06:57 225 查看
Binary Tree的深度优先搜索的一个很重要的思想就是分治了,先 divide 再 conquer。这是由二叉树的结构所决定的,左子树、右子树的结构特别适合分别找左、右的情况,然后再结合根节点合并起来。这就是分治思想。

下面是 Binary Search 的前序遍历情况:

public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(root == null){
return result;
}

List<Integer> left = preorderTraversal(root.left);
List<Integer> right = preorderTraversal(root.right);

result.add(root.val);
result.addAll(left);
result.addAll(right);
return result;

}
}


下面是Binary Tree Maximum path sum, 不吹不黑,真的难,真的难

public class Solution {

public class ResultType{
int singlePath, maxPath;

public ResultType(int single, int max){
this.singlePath = single;
this.maxPath = max;
}
}

private ResultType helper(TreeNode root){
if(root == null){
return new ResultType(0, Integer.MIN_VALUE);
}
//divide
ResultType left = helper(root.left);
ResultType right = helper(root.right);

//conquer
int SinglePath = Math.max(left.singlePath, right.singlePath) + root.val;
SinglePath = Math.max(SinglePath, 0);

int MaxPath = Math.max(left.maxPath, right.maxPath);
MaxPath = Math.max(MaxPath, left.singlePath + right.singlePath + root.val);

return new ResultType(SinglePath, MaxPath);
}

public int maxPathSum(TreeNode root) {
ResultType result = helper(root);
return result.maxPath;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息