美文网首页
【1错-1】Trim a Binary Search Tree

【1错-1】Trim a Binary Search Tree

作者: 7ccc099f4608 | 来源:发表于2019-01-19 22:45 被阅读0次

https://leetcode.com/problems/trim-a-binary-search-tree/

日期 是否一次通过 comment
2019-01-19 22:38 对preOrder & 分治理解不够深刻
image.png

(来源:https://leetcode.com/problems/trim-a-binary-search-tree/

  1. 非递归方法:TODO;
  2. 递归方法:
    2.1 递归思想:preOrder,首先判断root是否满足条件,再递归判断左右子树;

1. 非递归


2.1 递归

class Solution {
    public TreeNode trimBST(TreeNode root, int L, int R) {
        if(root == null) {
            return root;
        }
        
        if(root.val > R) {
            return trimBST(root.left, L, R);
        }
        
        if(root.val < L) {
            return trimBST(root.right, L, R);
        }
        
        root.left = trimBST(root.left, L, R);
        root.right = trimBST(root.right, L, R);
        
        return root;
        
    }
}

相关文章

网友评论

      本文标题:【1错-1】Trim a Binary Search Tree

      本文链接:https://www.haomeiwen.com/subject/vrrtjqtx.html