Binary Tree Preorder Traversal

Binary Tree Preorder Traversal


今天是一道有關(guān)基礎(chǔ)的題目,來(lái)自LeetCode,難度為Medium,Acceptance為37.8%。

題目如下


Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?

解題思路及代碼見(jiàn)閱讀原文

回復(fù)0000查看更多題目

解題思路


二叉樹的前序,中序,后續(xù)遍歷都是數(shù)據(jù)結(jié)構(gòu)課程的基礎(chǔ)了。

不做過(guò)多解釋了,大家權(quán)當(dāng)回憶一下大學(xué)時(shí)代吧。

代碼如下


Java版

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            if(null != root)
                stack.push(root);
            while(!stack.isEmpty()) {
                TreeNode node = stack.pop();
                list.add(node.val);
                if(node.right != null)
                    stack.push(node.right);
                if(node.left != null)
                    stack.push(node.left);
            }
            
            return list;
    }
}

關(guān)注我
該公眾號(hào)會(huì)每天推送常見(jiàn)面試題,包括解題思路是代碼,希望對(duì)找工作的同學(xué)有所幫助

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

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

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