leetcode144. 二叉树的前序遍历(迭代)
生活随笔
收集整理的這篇文章主要介紹了
leetcode144. 二叉树的前序遍历(迭代)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給定一個二叉樹,返回它的 前序 遍歷。示例:輸入: [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() {}* 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) {TreeNode next=root;List<Integer> res=new ArrayList<>();Stack<TreeNode> stack=new Stack<>();while (next!=null||!stack.isEmpty()){if(next==null) next=stack.pop();//左子樹已經(jīng)為空,就可以遍歷右子樹了res.add(next.val);if(next.right!=null) stack.push(next.right);//將右子樹入棧next=next.left;//先遍歷到的是左子樹}return res;} }總結
以上是生活随笔為你收集整理的leetcode144. 二叉树的前序遍历(迭代)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到穿红嫁衣是什么意思
- 下一篇: leetcode 1207. 独一无二的