黄哥Python: Binary Search Tree Iterator解题思路

257 阅读2分钟
原文链接: zhuanlan.zhihu.com

Leet Code 第173题Binary Search Tree Iterator 解题思路

Loading...leetcode.com图标

1、读题,题目要求为BST 实现一个迭代器,有二个方法,next 和hasNext 方法。

2、先按照中序遍历,变成一个数组或list等,再按照索引取值。

3、该题关键点是索引的边界条件。

下面黄哥用Python、Go、Java 三种语言实现的代码。

Python 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
# 黄哥Python培训 黄哥所写
class BSTIterator:

    def __init__(self, root: TreeNode):
      
        res = []
        def dfs(root):
            if root is None:
                return
            dfs(root.left)
            res.append(root.val)
            dfs(root.right)
        dfs(root)
        # print(res)
        self.nodes = res
        self.index = -1
            
        

    def next(self) -> int:
        """
        @return the next smallest number
        """
        self.index += 1 
        if self.index < len(self.nodes):

            return self.nodes[self.index]

Go 代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
// 黄哥Python培训 黄哥所写
type BSTIterator struct {
    nodes []int
    index int
}


func Constructor(root *TreeNode) BSTIterator {
    if root == nil {
        return BSTIterator{}
    }
    res := BSTIterator{
        index: -1,
    }
    dfs(root, &res)
    return res
}

func dfs(root *TreeNode, res *BSTIterator) {
    if root == nil {
        return
    }
    dfs(root.Left, res)
    res.nodes = append(res.nodes, root.Val)
    dfs(root.Right, res)
}


/** @return the next smallest number */
func (this *BSTIterator) Next() int {
    // fmt.Println(this.nodes)
    this.index += 1
    if this.index  < len(this.nodes) {
       return this.nodes[this.index]
       
    }
    this.index = -1
    return this.nodes[this.index]
    
}


/** @return whether we have a next smallest number */
func (this *BSTIterator) HasNext() bool {
    if this.index == len(this.nodes) - 1 {
        this.index += 1
    }
    if this.index >= -1 && this.index <= len(this.nodes) - 1 {
        return true
    }
    return false
    
}


/**

 * Your BSTIterator object will be instantiated and called as such:
 * obj := Constructor(root);
 * param_1 := obj.Next();
 * param_2 := obj.HasNext();
 */

Java 代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
// 黄哥Python培训 黄哥所写
class BSTIterator {
    List<Integer> nodes = new ArrayList<>();
    int index;
    public BSTIterator(TreeNode root) {
        dfs(root);
        index = -1;
    }
    public void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        nodes.add(root.val);
        dfs(root.right);
            
            
    }
    /** @return the next smallest number */
    public int next() {
        index += 1;
         if (index < nodes.size() ) {
             // return nodes[index];
             return nodes.get(index);
         }
         index = -1;
         return nodes.get(index);

            
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        if (index == nodes.size() - 1) {
                  index += 1;
        }
        if (index >= -1 && index <= nodes.size() - 1) {
            return true;
        }
        return false;
        }
}

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator obj = new BSTIterator(root);
 * int param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */
黄哥:黄哥Python:提醒要转行当程序员的朋友,学习要分先后主次zhuanlan.zhihu.com图标黄哥:黄哥Python培训是这样训练学员的zhuanlan.zhihu.com图标