Leetcode 144 二叉樹的前序遍歷

2022-09-14 01:57:12 字數 623 閱讀 4712

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

示例:輸入: [1,null,2,3] 1\

2/3 輸出: [1,2,3]

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

遞迴解法:

/*

* * definition for a binary tree node.

* struct treenode

* }; */

class

solution

void fdfs(treenode*root)

}void

init()

};

迭代演算法:

/*

* * definition for a binary tree node.

* struct treenode

* }; */

class

solution

void bfs(treenode*root)

root =fnum.top();

fnum.pop();

root = root->right;}}

void

init()

};

LeetCode 144 二叉樹的前序遍歷

1.題目 2.解答 2.1.遞迴法 定義乙個存放樹中資料的向量 data,從根節點開始,如果節點不為空,那麼 definition for a binary tree node.struct treenode class solution vectortemp if root null return...

LeetCode144 二叉樹的前序遍歷

題目描述 給定乙個二叉樹,返回它的前序遍歷。分析 遞迴演算法與非遞迴演算法。在非遞迴的方法中,使用輔助棧stack,右子樹先入棧左子樹 棧,就是根 左 右的順序。definition for a binary tree node.public class treenode 遞迴演算法 class s...

LeetCode 144 二叉樹的前序遍歷

給定乙個二叉樹,返回它的 前序 遍歷。示例 輸入 1,null,2,3 1 2 3 輸出 1,2,3 高階 遞迴演算法很簡單,你可以通過迭代演算法完成嗎?時間複雜度 o n 每個結點只會遍歷一次 空間複雜度 o n 遞迴實際上是要借助棧 definition for a binary tree no...