• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Leetcode 94: traversing binary tree in middle order (Java)

King Wang

1 月 3, 2022

LeetCode 94: Middle order traversal of binary trees (java)

subject :

answer :

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

 

发表回复