您的位置:首页 > 其它

661 - Convert BST to Greater Tree

2017-05-09 10:19 405 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: