二叉樹的前序遍歷(遞歸+迭代)

題目

給定一個二叉樹,返回它的 前序 遍歷。

示例:

輸入: [1,null,2,3]  
   1
    \
     2
    /
   3 

輸出: [1,2,3]

進階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?

遞歸

遞歸確實簡單,隨便寫一個。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    List<Integer> ans;
    
    public List<Integer> preorderTraversal(TreeNode root) {
        ans = new ArrayList<Integer>();
        dfs(root);
        return ans;
    }
    
    public void dfs(TreeNode root) {
        if (root == null) return ;
        ans.add(root.val);
        dfs(root.left);
        dfs(root.right);
    }
}

迭代1

這個迭代是自己寫的,思路也容易理解,就是把遞歸的順序用迭代實現了。把最左邊的節點先訪問了,然後再依據出棧順序訪問右孩子的最左邊的節點。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        
        vector<int> ans;
        stack<TreeNode*> nstack;
        if (root == nullptr) return ans;
        
	    // 最左邊的全都訪問入棧
        TreeNode *p = root;
        while (p) {
            nstack.push(p);
            ans.push_back(p->val);
            p = p->left;
        }
        
        // 每次出棧,若有右孩子,將其右孩子的最左邊全部訪問入棧
        while (!nstack.empty()) {
            p = nstack.top();
            nstack.pop();
            p = p->right;
            while (p) {
                nstack.push(p);
                ans.push_back(p->val);
                p = p->left;
            }
        }
        
        return ans;
    }
};

迭代2

這個迭代是力扣題解,巧妙用了入棧出棧順序,看起來優雅很多。

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        LinkedList<TreeNode> stack = new LinkedList<>();
        LinkedList<Integer> output = new LinkedList<>();
        if (root == null) {
            return output;
        }

        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pollLast();
            output.add(node.val);
            if (node.right != null) {
                stack.add(node.right);
            }
            if (node.left != null) {
                stack.add(node.left);
            }
        }
        return output;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章