java - Recusively Flipping a Binary Tree -
i have homework assignment in need flip binary tree. i'm not looking code or anything, hints why method not working.
below code. when step through it, seems work fine, flipping each left , right node, , moving through tree recursively. however, seems on return, it's returning node null left , right values, except original node (root).
public class treemanipulator<e> { public treemanipulator() { } public binarynode<e> fliptree(binarynode<e> _root) { binarynode<e> root = new binarynode<>(_root.getitem()); if (_root.getleft() != null) { root.setright(new binarynode<>(_root.getleft().getitem())); this.fliptree(_root.getleft()); } if (_root.getright() != null) { root.setleft(new binarynode<>(_root.getright().getitem())); this.fliptree(_root.getright()); } return root; } }
here main method:
public static void main(string[] args) { integer 1 = 1; integer 2 = 2; integer 3 = 3; integer 4 = 4; integer 5 = 5; integer 6 = 6; integer 7 = 7; integer 8 = 8; //root node = x binarynode<integer> x = new binarynode<>(one); //x.getleft = y binarynode<integer> y; //x.getright = z binarynode<integer> z; x.setleft(new binarynode<>(two)); x.getleft().setleft(new binarynode<>(six)); x.getleft().setright(new binarynode<>(seven)); x.setright(new binarynode<>(three)); x.getright().setright(new binarynode<>(four)); x.getright().setleft(new binarynode<>(five)); //set root children easier access z = x.getright(); y = x.getleft(); system.out.println(x.tostringpreorder()); //create tree manipulator treemanipulator flop = new treemanipulator(); binarynode<integer> flipped = flop.fliptree(x); system.out.println(flipped.tostringpreorder()); }
if need class 'binarynode', please ask, ill post it, did not want swap question code...
the input:
- input =
[ 1267354 ]
the expected output:
original tree =
[ 1267354 ]
after flip =
[ 1345276 ]
my output:
- after flip - '[ 132 ]'
i can't figure out why nodes '2', , '3' returning null left , right values.
you use recursion wrong, fliptree
doesn't flip object put it, returns flipped copy of original input. more don't put input child of root, put node containing value why you're getting tree depth 1 result.
this should fix problem:
public binarynode<e> fliptree(binarynode<e> _root) { binarynode<e> root = new binarynode<>(_root.getitem()); if (_root.getleft() != null) { root.setright(fliptree(_root.getleft()); } if (_root.getright() != null) { root.setleft(fliptree(_root.getright()); } return root; }
if want fliptree flip tree instead of returning flipped version have this:
public void fliptree(binarynode<e> root) { binarynode<e> temp = root.getleft(); root.setleft(root.getright()); root.setright(temp); if (root.getleft() != null) { fliptree(root.getleft()); } if (root.getright() != null) { fliptree(root.getright()); } }
btw, know said weren't looking code hints original code close hard give hint without immediatly fixing code.
Comments
Post a Comment