概述
题目链接:binary-tree-inorder-traversal
/**
*
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
2
/
3
return [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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/
2 3
/
4
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*
*/
public class BinaryTreeInorderTraversal {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
// 67 / 67 test cases passed.
// Status: Accepted
// Runtime: 216 ms
// Submitted: 1 minute ago
//简单的中序遍历
//递归版
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> inorder= new ArrayList<Integer>();
inorderTraversal(root, inorder);
return inorder;
}
public void inorderTraversal(TreeNode root, List<Integer> inorder) {
if (root != null) {
inorderTraversal(root.left, inorder);
inorder.add(root.val);
inorderTraversal(root.right, inorder);
}
}
//遍历版
public List<Integer> inorderTraversal1(TreeNode root) {
List<Integer> inorder= new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
while(!stack.isEmpty() || p != null) {
if(p != null) {
stack.add(p);
p = p.left;
} else {
TreeNode node = stack.pop();
inorder.add(node.val);
p = node.right;
}
}
return inorder;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
最后
以上就是危机草丛为你收集整理的94.Binary Tree Inorder Traversal的全部内容,希望文章能够帮你解决94.Binary Tree Inorder Traversal所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复