程式碼隨想錄 | 二元樹的遍歷

2022-10-10 06:01:36

二元樹的遞迴遍歷

遞迴的三要素

1.遞迴函數的引數和返回值

2.遞迴出口

3.單層遞迴的邏輯

144. 二元樹的前序遍歷

給你二元樹的根節點 root ,返回它節點值的 前序 遍歷。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        preoder(root,result);
        return result;
    }
    public void preoder(TreeNode node,List<Integer> result){
        if (node==null){
            return;
        }
        result.add(node.val);//前序遍歷:中、左、右
        preoder(node.left,result);
        preoder(node.right,result);
    }
}



94. 二元樹的中序遍歷

給定一個二元樹的根節點 root ,返回 它的 中序 遍歷 。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList();
        inorder(root,result);
        return result;
    }
    public void inorder(TreeNode node, List<Integer> result){
        if(node==null){
            return;
        }
        inorder(node.left,result);//中序遍歷:左、中、右
        result.add(node.val);
        inorder(node.right,result);
    }
}



145. 二元樹的後序遍歷

給你一棵二元樹的根節點 root ,返回其節點值的 後序遍歷 。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList();
        postorder(root,result);
        return result;
    }
    public void postorder(TreeNode node,List<Integer> result){
        if(node==null){
            return;
        }
        postorder(node.left,result);//後序遍歷:左、右、中
        postorder(node.right,result);
        result.add(node.val);
    }
}




二元樹的迭代遍歷

用棧操作,遞迴也是用棧實現的嘛