leedcode一刷--Binary Tree
2017-04-07 06:57
225 查看
Binary Tree的深度优先搜索的一个很重要的思想就是分治了,先 divide 再 conquer。这是由二叉树的结构所决定的,左子树、右子树的结构特别适合分别找左、右的情况,然后再结合根节点合并起来。这就是分治思想。
下面是 Binary Search 的前序遍历情况:
下面是Binary Tree Maximum path sum, 不吹不黑,真的难,真的难
下面是 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; } }
相关文章推荐
- Sicily 1210 二叉树 (Binary tree)
- POJ-2499 Binary Tree
- poj2499--Binary Tree
- Binary Tree(计算二叉树路径)
- binary tree
- 104. Maximum Depth of Binary Tree
- [leedcode 02] Add Two Numbers
- [leedcode 21] Merge Two Sorted Lists
- [leedcode 38] Count and Say
- [leedcode 58] Length of Last Word
- [leedcode 76] Minimum Window Substring
- [leedcode 92] Reverse Linked List II
- [leedcode 106] Construct Binary Tree from Inorder and Postorder Traversal
- [leedcode 120] Triangle
- [leedcode 137] Single Number II
- [leedcode 151] Reverse Words in a String
- [leedcode 187] Repeated DNA Sequences
- [leedcode 210] Course Schedule II
- [leedcode 228] Summary Ranges
- Binary tree 基础