您的位置:首页 > 其它

Flatten Binary Tree to Linked List ---LeetCode

2016-11-29 10:40 281 查看
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

解题思路:

遍历一遍树,如果根节点的右子节点不为空,将其入栈,并将左子节点移到右边,左边制空。当移到叶子节点时,再将栈里的节点依次弹出。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
if (root == null) return ;
Stack<TreeNode> stack = new Stack<>();

while (root != null || !stack.isEmpty()) {
if (root.right != null) {
stack.push(root.right);
}

if (root.left != null) {
root.right = root.left;
root.left = null;
} else if (!stack.isEmpty()) {
root.right = stack.pop();
}
root = root.right;
}
}
}


还有一种利用后序遍历递归的解法:

https://discuss.leetcode.com/topic/11444/my-short-post-order-traversal-java-solution-for-share

private TreeNode prev = null;

public void flatten(TreeNode root) {
if (root == null)
return;
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: