Tree Traversal without recursion and without stack and without changing the Tree - algorithm

This question is from the book Introduction to Algorithms 3rd:
**Each node in the binary tree has 4 properties: key,left,right,parent
EDIT: The binary tree is stored as linked nodes that each one of them has the 4 properties I mentioned.
Write an O(n) time nonrecursive procedure that, given an n-node binary tree,
prints out the key of each node. Use no more than constant extra space outside of the tree itself and do not modify the tree, even temporarily, during the procedure.
I tried to find a solution but got nothing...(Also I searched google for solutions for this book, but this question wasn't included there maybe because it was added in later versions).

Here's a solution:
Let current store the currently visited node (initialized to the root of the tree)
Let origin represent how we got to the current node. It's one of FROM_PARENT, FROM_LEFT_CHILD, FROM_RIGHT_CHILD. (Initialized to FROM_PARENT)
Algorithm:
If we came from the top, we print the key and go down left
If we came back from left, go down right
If we came back form right, go up.
origin = FROM_PARENT;
current = root;
while (current != null) {
switch (origin) {
case FROM_PARENT:
System.out.println(current.key);
if (current.left != null)
goLeft();
else
origin = FROM_LEFT_CHILD;
break;
case FROM_LEFT_CHILD:
if (current.right != null)
goRight();
else
origin = FROM_RIGHT_CHILD;
break;
case FROM_RIGHT_CHILD:
goToParent();
break;
}
}
Where
static void goToParent() {
if (current.parent == null) {
current = null;
return;
}
origin = current == current.parent.left ? FROM_LEFT_CHILD
: FROM_RIGHT_CHILD;
current = current.parent;
}
static void goLeft() {
origin = FROM_PARENT;
current = current.left;
}
static void goRight() {
origin = FROM_PARENT;
current = current.right;
}

Related

How would I code a method that finds the path of a maze/grid? What would I do after?

I want to implement a method that takes the starting and ending locations on a map and returns a path that navigates the map from start to end. (This path must not contain any impassable tiles (Wall tiles) and must be as short as possible.)
So for this implementation, I'm only allowed to use BFS. My first step would be to convert the maze into a graph but I'm not sure how to even start with that. Then I would have to run BFS on the tile containing the maze runner. Lastly, I would have to backtrack from the goal tile to build the path. There's so many steps I feel like I really need some help processing over this.
class GridLocation(val x: Int, val y: Int){
override def toString = s"($x, $y)"
override def equals(that: Any): Boolean = {
that match {
case other: GridLocation =>
this.x == other.x && this.y == other.y
case _ => false
}
}
}
object MapTile {
def generateRow(row: String): List[MapTile] = {
row.map((ch: Char) => MapTile(ch.toString)).toList
}
def apply(tileType: String): MapTile = {
tileType match {
case "-" => new MapTile("ground", true)
case "G" => new MapTile("goal", true)
case "O" => new MapTile("wall", false)
}
}
}
class MapTile(val tileType: String, val passable: Boolean) {
}
def findPath(start: GridLocation, end: GridLocation, map: List[List[MapTile]]): List[GridLocation] = {
//code starts here
}
Rather than explicitly building a graph, you can just keep the graph implicit by trying, at each cell, to move in each of the four cardinal directions [y+1,x],[y-1,x],[y,x+1],[y,x-1] and only add the new cell to the queue if it fulfills the following:
The new cell is within the grid and isn't a wall block.
The new cell hasn't been previously visited.
To keep track of visited cells, you can use an auxiliary array the size of the grid and mark visited cells off as 1 and unvisited as 0. Furthermore, to store the path, you can keep another auxiliary array that stores, for each cell, the "parent cell" that led directly to this cell, and upon finishing the BFS you can backtrack parents starting from the end cell all the way back to the start cell.
For clarity, the "parent cell" of cell x is the cell that was being considered when x was added to the queue.
I recommend you to look at A* algorithm, or an other "pathfinding" algorithm.
I think that the Youtube Channel "Coding train" had made a video on that.
Good afternoon.

Check of checkmate in chess

I am using this object oriented design of chess. I have implemented generating of valid moves for all pieces. Now I am trying implement check of checkmate.
I tried to make a method, which if player have moves, which cancel the checkmate. But the program end with StackOverflowError.
I delete the method. But the pseudoalgorithm of the method was something like that
boolean isGameOver(arg){
if(playerIsInCheck){
if(!hasValidMoves){
print("checkmate");
return true;
}
else{
return false;
}
}
else{
if(!hasValidMoves){
print("stalemate");
return true;
}
else{
return false;
}
}
}
I don't know how to check if the move cancel the checkmate. Can anyone advise me? I do not need all the code written in any programming language. Pseudoalgorithm will be sufficient.
The algorithm for checking for checkmate is as follows:
public boolean checkmated(Player player) {
if (!player.getKing().inCheck() || player.isStalemated()) {
return false; //not checkmate if we are not
//in check at all or we are stalemated.
}
//therefore if we get here on out, we are currently in check...
Pieces myPieces = player.getPieces();
for (Piece each : myPieces) {
each.doMove(); //modify the state of the board
if (!player.getKing().inCheck()) { //now we can check the modified board
each.undoMove(); //undo, we dont want to change the board
return false;
//not checkmate, we can make a move,
//that results in our escape from checkmate.
}
each.undoMove();
}
return true;
//all pieces have been examined and none can make a move and we have
//confimred earlier that we have been previously checked by the opponent
//and that we are not in stalemate.
}
I can't tell you why you are getting a stack overflow without seeing your method definitions, but I can explain how you check for mate-cancelling moves ( no pseudocode, sorry).
Basically, you generate a List of all possible Moves (Pseudolegals) and you let your programm try each of them. If the players king is no longer hittable in the resulting position (in your case you use the IsInCheck method), the current move is cancelling the mate.
If you do need the pseudocode, write a comment and I'll see what I can do.

Determining whether a node in a collapsible tree is hidden

I'm working on a GUI that displays a list of elements.
All the elements are in a one dimensional iterable array, so displaying them would normally look something like this:
foreach (Element e: elements) {
display.Display(e);
}
I now need a way to organize the elements in a tree structure like in this example:
In my system, there is no distinction between "folder" elements and "file" elements, but I can access an element's 'depth' and 'isExpanded' values.
How can I determine whether an element should be displayed based on data taken from iterating through previous elements?
I think I've figured it out, but there may be some cases that mess it up:
bool prevIsCollapsed = false;
int collapsedPropertyDepth = 0;
// iterate through each property of this component
for (Property p : properties)
{
int depth = property.depth;
if (prevIsCollapsed && depth > collapsedPropertyDepth)
{
// dont display this property
continue;
}
if (!property.isExpanded)
{
prevIsCollapsed = true;
collapsedPropertyDepth = depth;
}
else
{
prevIsCollapsed = false;
}
}

JFreeChart Performance

I'm trying to plot some graphs simultaneously:
Each representing an attribute and displays the results for several objects each containing its own data items series.
I encounter very bad performance using either add(...) or addOrUpdate(...) methods of the TimeSeries - time for plotting ~16,000 items is about 60 seconds.
I read about the performance issue - http://www.jfree.org/phpBB2/viewtopic.php?t=12130&start=0 - but it seems to me like it is much worse in my case for some reason.
I'd like to understand whether this is truly the performance that I may squeeze out of the module (2.5GHz machine running windows - I doubt that).
How can I get my application accelerated with this respect?
Here is a basic version of the code (note that it is all done in a dedicated thread):
/* attribute -> (Object -> graph values) */
protected HashMap<String,HashMap<Object,Vector<TimeSeriesDataItem>>> m_data =
new HashMap<String,HashMap<Object,Vector<TimeSeriesDataItem>>>();
public void loadGraph() {
int items = 0;
for (String attr : m_data.keySet())
for (Object obj : m_data.get(attr).keySet())
for (TimeSeriesDataItem dataItem : m_data.get(attr).get(obj))
items++;
long before = System.currentTimeMillis();
// plot each graph
for (String attr : m_data.keySet()) {
GraphXYPlot plot = m_plots.get(attr);
plot.addToObservation(m_data.get(attr));
}
System.err.printf("Time for plotting %d items is: %d ms", items, System.currentTimeMillis()-before);
// => Time for plotting 16540 items is: 59910 ms
}
public void addToObservation(HashMap<Object, Vector<TimeSeriesDataItem>> plotData) {
for (Object obj : plotData.keySet()) {
SeriesHandler handler = m_series.get(obj);
if (handler != null) {
TimeSeries fullSeries = handler.getFullSeries();
TimeSeries periodSeries = handler.getPeriodseries();
for (TimeSeriesDataItem dataItem : plotData.get(obj)) {
fullSeries.add(dataItem);
periodSeries.add(dataItem);
}
}
}
}
Thanks a lot !
Guy
Absent more details, any of several general optimizations should be considered:
Invoke setNotify(false), as suggested here.
Cache already calculated values, as discussed here.
Adopt a paging strategy, as shown here.
Chart a summary of average/time-unit values; based on the ChartEntity seen in a ChartMouseListener, show an expanded subset in an adjacent panel.

An array stack algorithm without copy

I have a flashlite3 application with navigation consisting of icons the user can browse left or right through infinitely.
The basic algorithm i'm using now works (and is adequate for this project) however, part of the solution depends on a duplicate of the array of icons. Depending on the number of items in the array, and/or the size of the element contents, this solution could become less efficient. I'm interested in a solution or algorithm(in any language) that could achieve the same thing while being scalable & efficient.
Heres a portion of relevant code in the setter function for mutating the '_selectedItem' property, which:
Evaluates the current '_selectedItem' and the new '_value'
Based on step 1 pop,unshifts right, or shift,pops left
Repeats step 2 until the icon matching the '_selectedItem' is in the center of the array
This code runs using 3 arrays:
[static] Array of positions. There are 5 icons, 3 are visible at a time, so position 0 is off stage, position 1 is 1/3, position 2 is 1/2 ..
When instantiating the icons 2 arrays are created: _viewArray & _icons. The order of _viewArray mimics the order to be displayed and _icons is left alone and used for the loop condition checking
///Actionscript2///
public function set selectedItem(value:Number)
{
var w=Stage.width;
if(value > _icons.length-1)
{
value=0;
}else if(value < 0)
{
value=_icons.length-1;
}
if(value > _selectedIndex)
{
while(_viewArray[Math.floor(_icons.length*.5)] != _icons[value])
{
var element;
element=_viewArray.pop();
_viewArray.unshift(element);
}
}else if(value < _selectedIndex)
{
while(_viewArray[Math.floor(_icons.length*.5)]!=_icons[value])
{
var element;
element=_viewArray.shift();
_viewArray.push(element);
}
}
for(var i:Number=0;i<_viewArray.length;i++)
{
if(i>=1 && i<= _icons.length-2)
{
_viewArray[i]._visible=true;
}else
{
_viewArray[i]._visible=false;
}
Tweener.addTween(_viewArray[i],{_x:positions[i],_alpha:80,time:.5,transition:'elasticIn'})
}
Tweener.addTween(_icons[(_viewArray.length*.5)-1],{_alpha:100,time:.0,transition:'elasticIn'});
Tweener.addTween(_selectedServiceIndicator,{_alpha:0,time:.3,transition:'elasticIn',onComplete:function() {Tweener.addTween(this,{_alpha:100,time:.2,transition:'elasticIn'});}});
var eventObject:Object = {target:this, type:'SelectedItemChange'};
eventObject.value=value;
for(var key in _serviceData[value])
eventObject[key]=_serviceData[value][key];
dispatchEvent(eventObject);
_selectedIndex=value;
}
Why does each element of the _viewArray has to actually store the icon, rather than only the index into the _icons array? This way you only have the icons stored once, and _viewArray just stores their presentation order.

Resources