通過查詢資料,主要有兩種風格的iterative solution for binary tree traversalhtml
For example, for the preorder traversal, there are two kinds of iterative solutions. Pay attention to the condition of the while loop:java
https://leetcode.com/problems/binary-tree-preorder-traversal/oop
http://blog.csdn.net/linhuanmars/article/details/21428647spa
List<Integer> res = new ArrayList<Integer>(); while(root!=null||!s.isEmpty()){ if(root!=null){ res.add(root.val); s.push(root); root = root.left; } else{ TreeNode n = s.pop(); root = n.right; } } return res;
https://algorithm.yuanbin.me/zh-hans/binary_tree/binary_tree_preorder_traversal.html.net
List<Integer> res = new ArrayList<Integer>(); if(root==null){ return res; } LinkedList<TreeNode> s = new LinkedList<TreeNode>(); s.push(root); while(!s.isEmpty()){ TreeNode n = s.pop(); res.add(n.val); if(n.right!=null){ s.push(n.right); } if(n.left!=null){ s.push(n.left); } } return res;
原本我以爲第二種方法好一些,但後來發現inorder用第二種方法很難作。因此爲了統一記憶方便,仍是都選用第一種只壓棧根節點作法吧!指針