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);
}
}
很巧妙地做法,采用右根左的中序遍历。
需要注意的是,采用非递归的方法时,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);
}
}
相关文章推荐
- LintCode 661 Convert BST to Greater Tree
- lintcode(661)Convert BST to Greater Tree
- 661.Convert BST to Greater Tree
- Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- leetcode: Convert BST to Greater Tree
- LintCode Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- LeetCode 538----Convert BST to Greater Tree
- LintCode-Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- LeetCode 538 Convert BST to Greater Tree(二叉树的右中左遍历)
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- Leetcode 538:Convert BST to Greater Tree
- Leetcode | Convert BST to Greater Tree