Binary Tree Non-recursive Traversal
Preorder:
因?yàn)槭莗reorder traversal, 我們需要先print root,然后左節(jié)點(diǎn),最后右節(jié)點(diǎn),而且root左邊子樹(shù)一定比右邊子樹(shù)先print出來(lái),所以,我們可以先把當(dāng)前root的右節(jié)點(diǎn)壓棧,然后把root的左節(jié)點(diǎn)壓棧,這樣每次從棧里取的時(shí)候,可以保證左邊節(jié)點(diǎn)的root先取。同時(shí),每次取了當(dāng)前節(jié)點(diǎn),我們進(jìn)行同樣的操作(先壓右節(jié)點(diǎn),再壓左節(jié)點(diǎn)),這樣可以保證preorder traversal。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();if (root == null) return list;Stack<TreeNode> s = new Stack<TreeNode>();s.push(root);while (!s.empty()) {TreeNode node = s.pop();list.add(node.val);if (node.right != null) {s.push(node.right);}if (node.left != null) {s.push(node.left);}}return list;} }Inorder:
因?yàn)閕norder 需要先打印最左邊,然后root,然后最右邊,所以,我們一定要先reach到樹(shù)的最左邊,直到?jīng)]有左子樹(shù)為止,并同時(shí)把root加入到stack里。
當(dāng)當(dāng)前node沒(méi)有左子樹(shù),表面我們已經(jīng)到達(dá)樹(shù)的最左邊,我們需要把stack最上面的root打出來(lái),然后當(dāng)前root指向root.right. 然后把右子樹(shù)當(dāng)成一顆樹(shù)使用同樣的遍歷即可。這題的關(guān)鍵點(diǎn)之一是那個(gè)while條件,也就是說(shuō),只要stack不為空或者當(dāng)前node不是null, 我們就應(yīng)該繼續(xù)。
class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();Stack<TreeNode> stack = new Stack<>();while(!stack.isEmpty() || root != null) {if (root != null) {stack.push(root);root = root.left;} else {root = stack.pop();list.add(root.val);root = root.right;}}return list;} }?
Postorder:
class Solution {public List<Integer> postorderTraversal(TreeNode root) {List<Integer> list = new LinkedList<>();if (root == null) return list;Stack<TreeNode> stack = new Stack<>();stack.push(root);while(!stack.isEmpty()) {root = stack.pop();list.add(0, root.val);if (root.left != null) { stack.push(root.left); }if (root.right != null) { stack.push(root.right); }}return list;} }?
轉(zhuǎn)載于:https://www.cnblogs.com/beiyeqingteng/p/5743214.html
總結(jié)
以上是生活随笔為你收集整理的Binary Tree Non-recursive Traversal的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Perl 之 use(), requir
- 下一篇: mac下对NTFS格式的磁盘进行读写操作