5 - Binary Tree & Tree-based DFS

Posted jenna

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
}

 

以上是关于5 - Binary Tree & Tree-based DFS的主要内容,如果未能解决你的问题,请参考以下文章

109. Convert Sorted List to Binary Search Tree

leetcode 94. Binary Tree Inorder Traversal

Construct Binary Tree from Preorder and Inorder Traversal

Binary Tree Traversal In Three Ways In Leetcode

99. Recover Binary Search Tre

Leetcode-993 Cousins in Binary Tree(二叉树的堂兄弟节点)