树的前序遍历算法:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if (root == null)
return;
TreeNode previous = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
if (root.right != null) stack.push(root.right);
if (root.left != null) stack.push(root.left);
while (!stack.empty()) {
TreeNode current = stack.pop();
previous.left = previous.right = null;
previous.right = current;
previous = current;
if (current.right != null) stack.push(current.right);
while (current.left != null) {
current = current.left;
previous.left = previous.right = null;
previous.right = current;
previous = current;
if (current.right != null) stack.push(current.right);
}
}
}
}
Run Status: Accepted!
Program Runtime: 684 milli secs
Program Runtime: 684 milli secs