剑指 Offer II 054. 所有大于等于节点的值之和(538. 把二叉搜索树转换为累加树 && 1038. 从二叉搜索树到更大和树)
题目:
思路:
【0】仔细认真观察其实就会发现一个规律,这个二叉搜索树的中序遍历是顺序的,而变更之后的更大和树的中序遍历,其实就是二叉搜索树中序遍历后,从后面往前面叠加的情况,如【0,1,2,3,4,5,6,7,8】变为【36,36,35,33,30,26,21,15,8】即 7+8 = 15 ,6+7+8=21,,5+6+7+8=26。。。。直到0+1+2+3+4+5+6+7+8=36
【1】深度搜索的方式(递归)
代码展示:
深度搜索的方式:
//简单展示版本 //时间0 ms击败100% //内存39.1 MB击败43.32% /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode bstToGst(TreeNode root) { ArrayList<TreeNode> treeList = new ArrayList<>(); middleDFS(root,treeList); int sum = 0; for (int i = treeList.size()-1; i >= 0;i--){ sum += treeList.get(i).val; treeList.get(i).val = sum; } return root; } public static void middleDFS(TreeNode root,ArrayList<TreeNode> list){ if (root == null) return; if (root.left != null) middleDFS(root.left,list); list.add(root); if (root.right != null) middleDFS(root.right,list); } } //优化的版本 //时间0 ms击败100% //内存38.8 MB击败91.29% class Solution { int sum = 0; public TreeNode bstToGst(TreeNode root) { if (root == null) { return null; } bstToGst(root.right); sum += root.val; root.val = sum; bstToGst(root.left); return root; } }
广度搜索的方式:
//时间3 ms击败7.46% //内存41.2 MB击败95.2% class Solution { public TreeNode convertBST(TreeNode root) { TreeNode head=root; if (root == null) { return root; } int sum = 0; List<TreeNode> list = new ArrayList<>(); Stack<TreeNode> queue = new Stack<>(); while (!queue.isEmpty() || root != null) { while (root != null) { queue.add(root); root = root.right; } root = queue.pop(); int n=root.val; root.val+=sum; sum += n; root = root.left; } return head; } }