0
点赞
收藏
分享

微信扫一扫

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

m逆光生长 2022-02-24 阅读 67

树数据结构:

 

例题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);
    }
}
举报

相关推荐

0 条评论