剑指 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);
    }
}
上一篇:Linux - ftp


下一篇:[LeetCode] 110. Balanced Binary Tree