【LeetCode】Binary Tree Inorder Traversal 二叉樹中序遍歷遞迴以及非遞迴演算法
阿新 • • 發佈:2019-01-07
Total Accepted: 16494 Total Submissions: 47494
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
{1,#,2,3}
,1 \ 2 / 3return
[1,3,2]
.Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
【解題思路】
1、遞迴
Java AC
2、非遞迴 棧儲存節點,當左孩子不為空,一直入棧。否則出棧,同時將棧頂元素存入list中,針對當前節點右孩子做同樣操作。/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private ArrayList<Integer> list; public ArrayList<Integer> inorderTraversal(TreeNode root) { list = new ArrayList<Integer>(); inOrder(root); return list; } private void inOrder(TreeNode root){ if(root == null){ return; } inOrder(root.left); list.add(root.val); inOrder(root.right); } }
Java AC
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private ArrayList<Integer> list; public ArrayList<Integer> inorderTraversal(TreeNode root) { list = new ArrayList<Integer>(); inOrder(root); return list; } private void inOrder(TreeNode root){ Stack<TreeNode> stack = new Stack<TreeNode>(); while(root != null || !stack.isEmpty()){ while(root != null){ stack.push(root); root = root.left; } if(!stack.isEmpty()){ root = stack.pop(); list.add(root.val); root = root.right; } } } }