94. Binary Tree Inorder Traversal

遞歸的代碼是以前數(shù)據(jù)結(jié)構(gòu)書上常見的:

    public ArrayList<Integer> inorderTraversal(ConstructBinaryTreefromPostorderandInorderTraversal.TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        dfs(res, root);
        return res;
    }

    private void dfs(List<Integer> res, ConstructBinaryTreefromPostorderandInorderTraversal.TreeNode node) {
        if (node == null) return;
        dfs(res, node.left);
        res.add(node.val);
        dfs(res, node.right);
    }

非遞歸用stack模擬中序遍歷,要理解啊,不能死記硬背。注意while條件和while里面的if。

public class Solution {
        public ArrayList<Integer> inorderTraversal(TreeNode root) {
            ArrayList<Integer> res = new ArrayList<>();
            LinkedList<TreeNode> stack = new LinkedList<>();
            //注意while條件是或
            while (root != null || !stack.isEmpty()){
                if (root!=null){
                    stack.push(root);
                    root = root.left;
                }else {
                    root = stack.pop();
                    res.add(root.val);
                    root = root.right;
                }
            }
            return res;
        }
}

MAR 25TH
這題今天做98. Validate Binary Search Tree 的時候又來復習了一遍,又忘的差不多了。。記得當時還在考慮為什么while里面要用||而不是&&。

這題還可以這樣寫:

public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    if(root == null) return list;
    Stack<TreeNode> stack = new Stack<>();
    while(root != null || !stack.empty()){
        while(root != null){
            stack.push(root);
            root = root.left;
        }
        root = stack.pop();
        list.add(root.val);
        root = root.right;
        
    }
    return list;
}

JULY 29 REVIEW

又看了一遍迭代的方法,仍然寫不出。。上面那個代碼,兩個while循環(huán)其實挺清晰的,但是root = root.right那邊還是挺難想到的。還有就是外層的while,兩種情況;1是root!= null的情況,這種比較好考慮,就是首次進入的時候;2是root==null的情況,statck不為空,這種就是dfs到棧最底的情況。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容