Binary Tree dfs Traversal
-preorder/inorder/postorder
-divide&conquer
-introduce dfs template
Preorder :
Inorder;
Postorder:
Divide & Conquer :
-Merge Sort (arrayO(N)空间, sorted list 不需要) 必会!待补充
-Quick Sort 必会!待补充
-Most of the Binary Tree Problem
题目:
1.Maximum Depth of Binary Tree
2.Balanced Binary Tree
3.Binary Tree Maximum Path Sum
public class Solution { int maxPath = Integer.MIN_VALUE; public int helper (TreeNode root) { if (root == null) { return 0; } int left = helper(root.left); int right = helper(root.right); maxPath = Math.max(maxPath, Math.max(root.val, Math.max(root.val + left + right, Math.max(root.val + left, root.val + right)))); return Math.max(root.val, Math.max(root.val + left, root.val + right));//第一遍写成return maxPath;? } public int maxPathSum(TreeNode root) { helper(root); return maxPath; } }
黄老师不用全局变量版本:
public class Solution { public class ResultType { int singlePath, maxPath; ResultType(int singlePath, int maxPath) { this.singlePath = singlePath; this.maxPath = maxPath; } } public ResultType helper (TreeNode root) { if (root == null) { return new ResultType(0, Integer.MIN_VALUE); } ResultType left = helper(root.left); ResultType right = helper(root.right); int single = Math.max(left.singlePath, right.singlePath) + root.val; single = Math.max(single, 0); int max = Math.max(left.maxPath, right.maxPath); max = Math.max(max, left.singlePath + right.singlePath + root.val); return new ResultType(single, max); } public int maxPathSum(TreeNode root) { ResultType res = helper(root); return res.maxPath; } }
DFS Template:
Template 1: Traverse public class Solution { public void traverse(TreeNode root) { if (root == null) { return; } // do something with root traverse(root.left); // do something with root traverse(root.right); // do something with root } } Tempate 2: Divide & Conquer public class Solution { public ResultType traversal(TreeNode root) { // null or leaf if (root == null) { // do something and return; } // Divide ResultType left = traversal(root.left); ResultType right = traversal(root.right); // Conquer ResultType result = Merge from left and right. return result; } }
4.Binary Tree Level Order Traversal
public class Solution { public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if (root == null) { return res; } Queue<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); while (!q.isEmpty()) { ArrayList<Integer> level = new ArrayList<Integer>(); int size = q.size(); for (int i = 0; i < size; i++) { TreeNode r = q.poll(); level.add(r.val); if (r.left != null) { q.add(r.left); } if (r.right != null) { q.add(r.right); } } res.add(level); } return res; } }
时间: 2024-12-19 10:06:50