力扣-->#剑指Offer 897 . 递增顺序搜索树(E)

力扣-->#剑指Offer 897 . 递增顺序搜索树(E)_第1张图片

 

class Solution {
    TreeNode curr;
    public TreeNode increasingBST(TreeNode root) {
        TreeNode first = new TreeNode(-1);
        
        //用first 来记录curr的初始位置
        curr = first;

        dfs(root);
        
        return first.right;
    }
    
    private void dfs(TreeNode node){
        if(node == null) return;
        
        dfs(node.left);
    
        curr.right = new TreeNode(node.val);
        
        //指针向树的右边移动
        curr = curr.right;
        
        dfs(node.right);
    }
}

你可能感兴趣的:(算法,leetcode,算法,职场和发展)