Is there any java solution to reduce the time to traverse preorder binary tree?
When I decide to traverse the binary tree after the order for the first time, I only use one stack to store the node and use one List as the result. So the time complexity is obviously N ^ 2. But if you use 2 stacks, the time complexity can be simplified to N.
As far as order traversal goes, I think one stack is enough. But my decision time is still average.
So is there any solution to improve it? Below is my code:
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> nodes = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
if (root == null)
return result;
nodes.push(root);
while (!nodes.isEmpty()) {
TreeNode temp = nodes.pop();
result.add(temp.val);
if (temp.right != null) {
nodes.push(temp.right);
}
if (temp.left != null) {
nodes.push(temp.left);
}
}
return result;
}
}
Thank!
+3
source to share
No one has answered this question yet
Check out similar questions: