思路:
前序遍历路径上节点的值先放入list,然后把节点的right-child放入栈,一次前序遍历到叶节点的时候,去栈中取出节点,循环进行前序遍历到叶节点。最后返回list
public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if(root == null) { return result; } TreeNode node = null; stack.add(root); while(!stack.empty()) { node = stack.pop(); while(node != null) { result.add(node.val); if(node.right != null) { stack.push(node.right); } node = node.left; } } return result; } }
非递归中序遍历如下
public ArrayList<Integer> inorderTraversal(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if(root == null) { return result; } stack.add(root); TreeNode node = root.left; while(!stack.empty() || node != null) { //第二个条件意义{1,#,2} while(node != null) { stack.add(node); node = node.left; //左子树遍历到头,依次入栈 } node = stack.pop(); result.add(node.val); node = node.right; //右子树遍历 } return result; }
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }