LeetCode - 連結串列 - 144. 二叉樹的前序遍歷
阿新 • • 發佈:2021-02-13
技術標籤:LeetCode - 樹leetcode
144. 二叉樹的前序遍歷
https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
給你二叉樹的根節點 root ,返回它節點值的 前序 遍歷。
示例1
輸入:root = [1,null,2,3]
輸出:[1,2,3]
示例2:
輸入:root = []
輸出:[]
示例 3:
輸入:root = [1]
輸出:[1]
示例 4:
輸入:root = [1,2]
輸出:[1,2]
示例 5:
輸入:root = [1,null,2]
輸出:[1,2]
提示:
樹中節點數目在範圍 [0, 100] 內
-100 <= Node.val <= 100
遞迴方法:
虛擬碼
- 定義一個LinkedList 私有變數 result 存放輸出結果
- 判斷根節點是否為空,為空則直接返回result
- 不為空則訪問節點(即將值存入 result)
- 然後繼續遞迴訪問 左子節點
- 然後繼續遞迴訪問 右子節點
- 返回 result
/**
* 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 {
private static List<Integer> result = new LinkedList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null) return null;
result.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right) ;
return result;
}
}
迭代方法
虛擬碼
- 定義一個棧stack,用來實現訪問順序
- 定義一個LinkedList 私有變數 result 存放輸出結果
- 判斷根節點是否為空,為空直接返回 result
- 定義一個node節點,並 node = root;
- 迴圈操作[node != null]
訪問node節點,將node 的右子節點入棧,設定node = node.lef;
直到 node == null - 如果棧為空,為空則結束遍歷
- 如果棧不為空,則執行迴圈操作(stack.size() != null)
彈出棧頂元素 top,進行訪問
將 node.right 入棧,將node.left 入棧
直至棧為空則結束
public static List<Integer> preorderTraversal2(TreeNode root) {
if(root == null) return result;
TreeNode node = root;
while (node != null){
result.add(node.val);
if(node.right!=null) {
stack.add(node.right);
}
node = node.left;
}
while(!stack.isEmpty()){
node = stack.pop();
result.add(node.val);
if(node.right != null){
stack.add(node.right);
}
if(node.left != null){
stack.add(node.left);
}
}
return result;
}