【面试算法题总结12】树数据结构

树数据结构:

 

例题1:把二叉搜索树转换为累加树

让我们逆中序遍历一下

/**
 * 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 {
    int pre=0;
    public TreeNode convertBST(TreeNode root) {
        dfs(root);
        return root;
    }
    //这里我们逆中序遍历一下
    void dfs(TreeNode root){
        if(root==null){
            return;
        }
        dfs(root.right);
        root.val+=pre;
        pre=root.val;
        dfs(root.left);
    }
}
上一篇:打印九九乘法表


下一篇:Elastic Stack日志分析(十)- Elasticsearch数据路由详解