zoukankan      html  css  js  c++  java
  • [LeetCode] 538. 把二叉搜索树转换为累加树 ☆(中序遍历变形)

    把二叉搜索树转换为累加树

    描述

    给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

    例如:

    输入: 二叉搜索树:
    5
    /
    2 13

    输出: 转换为累加树:
    18
    /
    20 13

    解析

    标准中序遍历,再反着遍历,每个节点的值 += 前一个节点的值。

    代码

    傻方法

    先把树,左右全部交换,再标准中序遍历,再左右交换回来。

    public TreeNode convertBST(TreeNode root) {
            if (null == root) {
                return null;
            }
            swap(root);
            TreeNode temp = root;
            int preVal = 0;
            Stack<TreeNode> stack = new Stack<>();
            while (!stack.isEmpty() || null != temp) {
                if (null != temp) {
                    stack.push(temp);
                    temp = temp.left;
                } else {
                    TreeNode curNode = stack.pop();
                    curNode.val += preVal;
                    preVal = curNode.val;
                    temp = curNode.right;
                }
            }
            return root;
        }
    
        public void swap(TreeNode root) {
            if (null == root) {
                return;
            }
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
            swap(root.left);
            swap(root.right);
        }

    中序遍历变形--栈迭代

    public TreeNode convertBST(TreeNode root) {
            if (null == root) {
                return null;
            }
            TreeNode temp = root;
            int preVal = 0;
            Stack<TreeNode> stack = new Stack<>();
            while (!stack.isEmpty() || null != temp) {
                if (null != temp) {
                    stack.push(temp);
                    temp = temp.right;
                } else {
                    TreeNode curNode = stack.pop();
                    curNode.val += preVal;
                    preVal = curNode.val;
                    temp = curNode.left;
                }
            }
            return root;
        }

    中序遍历变形--递归

        private int sum = 0;
        public TreeNode convertBST(TreeNode root) {
            if (root != null) {
                convertBST(root.right);
                sum += root.val;
                root.val = sum;
                convertBST(root.left);
            }
            return root;
        }
  • 相关阅读:
    A1132 Cut Integer (20分)
    A1131 Subway Map (30分)
    A1130 Infix Expression (25分)
    A1129 Recommendation System (25分)
    A1128 N Queens Puzzle (20分)
    arm指令集
    韦东山视频地址
    汇编知识
    emacs 使用教程
    ip
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/12063349.html
Copyright © 2011-2022 走看看