其他分享
首页 > 其他分享> > 剑指 Offer II 052. 展平二叉搜索树

剑指 Offer II 052. 展平二叉搜索树

作者:互联网

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private TreeNode curr;
    public TreeNode increasingBST(TreeNode root) {
        TreeNode res = new TreeNode();
        curr = res;
        //创建一个辅助结点 curr指向辅助结点
        //最后 curr将指向最后一个结点
        res.right = root;
        inorder(root);
        return res.right;
    }
    public void inorder(TreeNode node){
        if(node==null) return;

        inorder(node.left);
        curr.right = node;
        //让curr(上半部分的最后一个结点)的右子树指向该结点
        //因为左子树最先开始遍历
        //注意这时候左子树的部分已经放进了结果中
        node.left = null;
        //让该节点的左子树为空即可
        curr = node;
        inorder(node.right);
    }
}

标签:node,right,TreeNode,val,Offer,展平,II,curr,left
来源: https://blog.csdn.net/qq_37772958/article/details/122312637