Leetcode-144 Binary Tree Preorder Traversal Solution in Java | Hindi Coding Community

0

 

Given the root of a binary tree,you have to return the preorder traversal of its nodes' values. Find the preorder of this binary tree.

 

Example 1:

Input: root = [1,null,2,3]
Output: [1,2,3]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
Java Code :



class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> al=new ArrayList<Integer>();
Stack<TreeNode> st=new Stack<TreeNode>();
TreeNode curr=root;
st.push(root);
while(!st.isEmpty())
{
while(curr!=null)
{
al.add(curr.val);
if(curr.right!=null)
{
st.push(curr.right);
}
curr=curr.left;
}
curr=st.pop();
}
return al;
}
}







Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !