5 - Binary Tree & Tree-based DFS

900. Closest Binary Search Tree Value

https://www.lintcode.com/problem/closest-binary-search-tree-value/description?_from=ladder&&fromId=1

1. 非递归方法:求BST中跟target最近的数字。我们先设置一个min = root.val, 然后用iterative的方法尝试更新min,然后比较target与root的大小,进行二分查找。

public int closestValue(TreeNode root, double target) {
        // write your code here
       int min = root.val;
        while(root != null) {
            min = Math.abs(target - root.val) < Math.abs(target - min) ? root.val : min;
            root = root.val > target ? root.left : root.right;
        }
        return min;
    }

2. 递归

  1. 比较target和root.val, => 求child是为了递归

  2. if(child == null) return root.val;

  3. 求 childClosest = closestValue(child, target)

  4. 比较 root.val 和childClosest

public int closestValue(TreeNode root, double target) {
        // write your code here
        TreeNode child = root.val > target ? root.left : root.right;
        if(child == null) {
            return root.val;
        }
        int childClosest = closestValue(child, target);
        return Math.abs(root.val - target) > Math.abs(childClosest - target) ? childClosest : root.val;
    }

596. Minimum Subtree

https://www.lintcode.com/problem/minimum-subtree/description?_from=ladder&&fromId=1

public class Solution {
    /**
     * @param root: the root of binary tree
     * @return: the root of the minimum subtree
     */
    public TreeNode findSubtree(TreeNode root) {
        // write your code here
        ResultType result = helper(root);
        return result.minSubtree;
    }
    
    public ResultType helper(TreeNode node) {
        if(node == null) {
            return new ResultType(null, Integer.MAX_VALUE, 0);
        }
        
        ResultType leftResult = helper(node.left);
        ResultType rightResult = helper(node.right);
        
        ResultType result = new ResultType(
          node,
          leftResult.sum + rightResult.sum + node.val,
          leftResult.sum + rightResult.sum + node.val
        );
        
        if(leftResult.minSum <= result.minSum) {
            result.minSum = leftResult.minSum;
            result.minSubtree = leftResult.minSubtree;
        }
        
        if(rightResult.minSum <= result.minSum) {
            result.minSum = rightResult.minSum;
            result.minSubtree = rightResult.minSubtree;
        }
        
        return result;
    }
}

猜你喜欢

转载自www.cnblogs.com/jenna/p/10804263.html
今日推荐