Binary Tree Traversal - two styles of solutions

通過查詢資料,主要有兩種風格的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

1.指針遍歷同時壓棧根節點法 while(root!=null||!s.isEmpty()):

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;

2. 先壓棧子節點後彈棧遍歷法while(!s.isEmpty()):

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用第二種方法很難作。因此爲了統一記憶方便,仍是都選用第一種只壓棧根節點作法吧!指針

相關文章
相關標籤/搜索