码迷,mamicode.com
首页 > 其他好文 > 详细

5 - Binary Tree & Tree-based DFS

时间:2019-05-03 09:48:33      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:nod   https   href   ini   mini   ntc   数字   color   bst   

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;
    }
}

 

5 - Binary Tree & Tree-based DFS

标签:nod   https   href   ini   mini   ntc   数字   color   bst   

原文地址:https://www.cnblogs.com/jenna/p/10804263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!