661

来源:互联网 发布:剑灵天女短发捏脸数据 编辑:程序博客网 时间:2024/06/10 15:12

5.9

很巧妙地做法,采用右根左的中序遍历。

需要注意的是,采用非递归的方法时,sum应该设置为全局变量,刚开始忽略了这一点。

还有就是二叉树的各种遍历的方法,好长时间没有写了,都有点儿生疏了。

/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {    /**     * @param root the root of binary tree     * @return the new root     */    public TreeNode convertBST(TreeNode root) {        // Write your code here        if(root == null){            return root;        }        inOrder1(root);        return root;    }    // 采用 右根左的遍历顺序 - 非递归的方式    public void inOrder(TreeNode root){        TreeNode bt = root;        int sum = 0;        LinkedList<TreeNode> list = new LinkedList<TreeNode>();        while(bt != null || !list.isEmpty()){            while(bt != null){                list.push(bt);                bt = bt.right;            }            if(!list.isEmpty()){                bt = list.pop();                bt.val = bt.val + sum;                sum = bt.val;                bt = bt.left;            }        }    }       // 采用 右根左的遍历顺序 - 递归的方式    private int sum = 0;    public void inOrder1(TreeNode root){        if(root == null){            return;        }        inOrder1(root.right);        root.val = root.val + sum;        sum = root.val;        inOrder1(root.left);    }}


0 0
原创粉丝点击